<?php

namespace Home\Controller;

require_once dirname(__FILE__) . '/../../../../vendor/workerman/gatewayclient/Gateway.php';

use GatewayClient\Gateway;
use Home\Model\TaskDailyModel;
use Think\Controller;
use Common\Service\TencentIM;
use Think\Log;

include_once("mysqlha.php");
include_once("Common.php");
header("Content-type:text/html;charset=utf-8");

class PrivatechatController extends CommonController
{
    
    public  function common_redis(){
        $user_id =20380874;
        $commonRedis =apisCommonRedis();
        $data =  $commonRedis->get('user_online:user_is_online_'.$user_id);
        echo  $data;
    }
    public function chatList($userid, $first=0, $page=0): array
    {
        $userInfo = M('user')->where(['id'=>$userid])->field('id, sex, reg')->cache(true,86400)->find();
        $config = M('config_system')->where(['category' => ['in', ['kefu']]])->cache(true,3600)->getField('title, content');
        $kefu = intval($config['id']);
        if ($first) {
            $page = $page ?: 1;
            $page = ($page - 1) * 20;
            $limit = " limit $page, 20";
        } else {
            $limit = '';
        }
        if ($userInfo['reg'] == 2) {
        }
        if($kefu == $userid){
            $sql = "(SELECT *, user_time time FROM chat_lists WHERE user_id = $userid and user_delete = 0 order by user_time desc, id desc) UNION (SELECT *, another_time time FROM chat_lists WHERE another_id = $userid and another_delete = 0 order by another_time desc, id desc) order by time desc, id desc $limit";
        }elseif($userInfo['sex'] == '女'){
            $sql = "(SELECT *, user_time time FROM chat_lists WHERE user_id = $userid and user_delete = 0 and user_first = $first order by user_time desc, id desc) UNION (SELECT *, another_time time FROM chat_lists WHERE another_id = $userid and another_delete = 0 and another_first = $first order by another_time desc, id desc) order by time desc, id desc $limit";
            if ($userInfo['reg'] == 2) {
                $sql = "(SELECT *, user_time time FROM chat_lists WHERE user_id = $userid and user_delete = 0 order by user_time desc, id desc) UNION (SELECT *, another_time time FROM chat_lists WHERE another_id = $userid and another_delete = 0 order by another_time desc, id desc) order by time desc, id desc $limit";
            }
        }else{
            $sql = "(SELECT *, user_time time FROM chat_lists WHERE user_id = $userid and user_delete = 0 and another_first = $first  order by user_time desc, id desc) UNION (SELECT *, another_time time FROM chat_lists WHERE another_id = $userid and another_delete = 0 and user_first = $first order by another_time desc, id desc) order by time desc, id desc $limit";
            if ($userInfo['reg'] == 2) {
                $sql = "(SELECT *, user_time time FROM chat_lists WHERE user_id = $userid and user_delete = 0 order by user_time desc, id desc) UNION (SELECT *, another_time time FROM chat_lists WHERE another_id = $userid and another_delete = 0 order by another_time desc, id desc) order by time desc, id desc $limit";
            }
        }

        // var_dump($sql);exit;
        $data = M()->master(true)->Query($sql);

        if ($data) {
            //$gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->cache(true,3600)->getField('id, icon, circle');
            $gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->cache(true,3600)->getField('id, icon, circle');
            $uids = [];
            $uidmins = [];
            $uidmaxs = [];
            foreach ($data as $key => $item) {
                if ($item['user_id'] == $userid) {
                    $uv = $item['another_id'];
                } else {
                    $uv = $item['user_id'];
                }
                $uids[] = $uv;
                if ($uv > $userid) {
                    $uidmaxs[] = $uv;
                } else {
                    $uidmins[] = $uv;
                }
            }

            // $userstr = implode(',', $uids);
            // $users = S('userinfos:'.$userstr);

            // if(!$users){
                $users = M('user')->where(['id' => ['in', $uids], 'delete_time' => 0])->getField('id, head_100, name, sex, age, city, is_identity_authentication, noble_grade, noble_time, is_online, real_avatar, register_datetime,entertainment,entertainment_child, last_login_datetime,is_banned,banned_end_time,delete_time,is_online,is_hide');
                // S('userinfos:'.$userstr, $users, 300);
            // }
            $timenow = time();
            $roles = M('user_entertainment')->cache(true,600)->getField('id, name');
            $roles_top = ['娱乐','分享','交友','找对象'];
            foreach ($users as &$value) {
                if ($value['is_banned'] == 1) {
                // if ($value['is_banned'] == 1 && strtotime($value['banned_end_time']) > $timenow) {
                    $value['is_online'] = 0;
                    continue;
                }
                if ($value['is_online'] == 0) {
                    if ($timenow - 1*86400 < strtotime($value['last_login_datetime'])) {
                        $value['is_online'] = 1;
                    }
                }
            }

            $remarkname = M('chat_charge_records')->master(true)->where([['user_id'=>['in', $uidmins], 'another_id'=>$userid], ['user_id'=>$userid, 'another_id'=>['in', $uidmaxs]], '_logic' => 'OR'])->cache(true)->getField('user_id,another_id,user_remark,another_remark', true);
            $remarknames = [];
            foreach ($remarkname as $rnk => $rnv) {
                if ($rnv['user_id'] == $userid) {
                    $remarknames[$rnv['another_id']] = $rnv['another_remark'];
                } else {
                    $remarknames[$rnv['user_id']] = $rnv['user_remark'];
                }
            }

            $today_start = strtotime(date('Ymd'));
            $time = time();

            $kefus = [];
            $contain1 = [];
            $contain2 = [];
            foreach ($data as $key => $item) {
                $another_id = $item['user_id'] == $userid ? $item['another_id'] : $item['user_id'];

                if (isset($users[$another_id])) {
                    $user = $users[$another_id];

                    $field = $item['user_id'] == $userid ? 'user_' : 'another_';

                    $data[$key]['content'] = $item[$field . 'content'];
                    $data[$key]['userid'] = $item['user_id'] == $userid ? $item['another_id'] : $item['user_id'];
                    $data[$key]['touserid'] = $item['user_id'] == $userid ? $item['another_id'] : $item['user_id'];
                    $data[$key]['type'] = $item[$field . 'channel'];
                    $data[$key]['count'] = $item[$field.'unread'];
                    $data[$key]['isRead'] = $item[$field.'unread'] ? 1 : 0;
                    $data[$key]['sort'] = $item[$field . 'top'] ? $item[$field . 'time'] + 1000000000 : $item[$field . 'time'];
                    $data[$key]['top'] = $item[$field . 'top'];


                    if ($item[$field . 'time'] >= $today_start) {
                        $data[$key]['addtime'] = date('H:i', $item[$field . 'time']);
                    } else if ($item[$field . 'time'] >= ($today_start - 86400)) {
                        $data[$key]['addtime'] = '昨天';
                    } else {
                        $data[$key]['addtime'] = date('Y/m/d', $item[$field . 'time']);
                    }

                    $data[$key]['is_cluster'] = 0;
                    $data[$key]['cluster_types'] = 0;
                    $data[$key]['noble_circle'] = '';

                    if ($user['noble_grade'] && $user['noble_time'] > $time) {
                        $data[$key]['noble_icon'] = $gradeNoble[$user['noble_grade']] ? changeUrl($gradeNoble[$user['noble_grade']]['icon']) : '';
                    } else {
                        $data[$key]['noble_icon'] = '';
                    }

                    $data[$key]['real_avatar'] = $user['real_avatar'];
                    $data[$key]['name'] = isset($remarknames[$user['id']]) && $remarknames[$user['id']] ? $remarknames[$user['id']] : $user['name'];
                    $data[$key]['sex'] = $user['sex'];
                    $data[$key]['register_datetime'] = $user['register_datetime'];
                    $data[$key]['age'] = $user['age'];
                    $data[$key]['entertainment'] = $user['entertainment'] ?? 0;
                    $data[$key]['entertainment_text'] = $roles_top[$user['entertainment']] ?? 0;
                    $data[$key]['entertainment_child'] = $user['entertainment_child'] ?? 0;
                    $data[$key]['entertainment_child_text'] = $user['entertainment_child'] ? getRoles($user['entertainment_child'], $roles) : '';
                    $data[$key]['is_online'] = $user['is_online'];
                    // $data[$key]['is_online'] = 0;
                    $data[$key]['kefu'] = $user['id'] == $kefu ? 1 : 0;
                    $data[$key]['is_identity_authentication'] = $user['is_identity_authentication'];
                    $data[$key]['sumb_headimg'] = $user['head_100'];
                    $data[$key]['city_mask'] = $user['city'] ?? '';
                    $data[$key]['city'] = '';
                    $data[$key]['intimate'] = 0;
                    
                    $data[$key]['delete_time']=$user['delete_time']; //>0表示账户已注销
                    $data[$key]['is_online']=$user['is_online']; //是否在线
                    $data[$key]['is_hide']=$user['is_hide']; //是否隐藏在线状态

                    unset($data[$key]['another_id'], $data[$key]['user_content'], $data[$key]['another_content'], $data[$key]['user_channel'], $data[$key]['another_channel'],
                        $data[$key]['user_unread'], $data[$key]['another_unread'], $data[$key]['user_untip'], $data[$key]['another_untip'], $data[$key]['user_delete'],
                        $data[$key]['another_delete'], $data[$key]['user_top'],$data[$key]['user_time'], $data[$key]['another_time'], $data[$key]['user_id'],
                        $data[$key]['another_top'], $data[$key]['time'], $data[$key]['user_first'], $data[$key]['another_first']);

                    if ($userid == $kefu) {
                        if ($user['id'] == $kefu) {
                            $item['city'] = '';
                            $kefus[] = $data[$key];
                        } else if (!$data[$key]['is_cluster'] && $data[$key]['touserid'] == $kefu) {
                            $contain1[] = $data[$key];
                        } else {
                            $contain2[] = $data[$key];
                        }
                    } else {
                        $contain2[] = $data[$key];
                    }
                }
            }

            array_multisort(array_column($kefus, 'sort'), SORT_DESC, $kefus);
            array_multisort(array_column($contain1, 'sort'), SORT_DESC, $contain1);
            array_multisort(array_column($contain2, 'sort'), SORT_DESC, $contain2);

            $data = array_merge($kefus, $contain1, $contain2);
            
            if (count($data) > 150) {
                $output = array_slice($data, 150);
    
                $update_user = [];
                $update_another = [];
                foreach ($output as $item) {
                    if ($item['userid'] > $userid) {
                        $update_user[] = $item['id'];
                    } else {
                        $update_another[] = $item['id'];
                    }
                }
                
                if ($update_user) {
                    M('chat_lists')->where(['id' => ['in', $update_user]])->save(['user_unread' => 0, 'user_delete' => 1]);
                }
                if ($update_another) {
                    M('chat_lists')->where(['id' => ['in', $update_another]])->save(['another_unread' => 0, 'another_delete' => 1]);
                }
            }

            return $data;
        } else {
            return [];
        }
    }

   public function getreadcount($data)
    {
        $data = json_decode($data, true);
        $user_id_real = $user_id = $data['user_id'] ?? 6374;
        $res = (new TencentIM)->get_list($user_id);
        if (isset($res['SessionItem']) && !empty($res['SessionItem'])){
            $To_Accounts = array_column($res['SessionItem'], 'To_Account');
            $unreads = (new TencentIM)->get_c2c_unread_msg_num($user_id, $To_Accounts);
            $unread1 =  array_sum($unreads)?? 0;
        }else{
            $unread1 = 0;
        }
        $user = M('user')->field('id, sex, register_datetime, reg, authcode')->cache(true,86400)->where(['id' => $user_id])->find();
        // $sql = "(SELECT sum(user_untip) untip FROM chat_lists WHERE user_id = $user_id_real and user_delete = 0) UNION (SELECT sum(another_untip) untip FROM chat_lists WHERE another_id = $user_id_real and another_delete = 0)";
        // $chat_lists = M()->Query($sql);
        // $untip1 = $chat_lists[0]['untip'] + $chat_lists[1]['untip'];
        
        // $chat_lists_user_untip = M('chat_lists')->where(['user_id' => $user_id_real,'user_delete'=>0])->sum('user_untip');
        // $chat_lists_another_untip = M('chat_lists')->where(['another_id' => $user_id_real,'another_delete'=>0])->sum('another_untip');
        // $untip1 = $chat_lists_user_untip + $chat_lists_another_untip;
    
        $unread3 = 0;
        // $channel = $user['sex'] == '男' ? [1,2] : [1,3];
        // $where = ['channel' => ['in', $channel], 'sys_channel'=>['in', [0,getenv('APP_CHANNEL')]]];
        // $where['_string'] = "(type=0 and (is_top = 1 or create_time >= '" . $user['register_datetime'] . "')) or (to_user=".$user['id']." and type = 32)";
        // $message = M('sys_message')->where($where)->order('is_top desc, id desc')->limit(20)->getField('id', true);
        // if ($message) {
        //     $read_count = M('sys_message_read')->where(['user_id' => $user_id_real, 'message_id' => ['in', $message]])->count();
        //     $unread2 = count($message) - $read_count;
        // } else {
        //     $unread2 = 0;
        // }
           $unread2 =0;
        //  $sound_tip = $untip1;

        $chat_lists_user_untip =   M('chat_lists')->where(['user_id' =>$user_id,'user_untip'=>['gt',0]])->save(['user_untip' => 0]);
        $chat_lists_another_untip =   M('chat_lists')->where(['another_id' =>$user_id,'another_untip'=>['gt',0]])->save(['another_untip' => 0]);

        if ($chat_lists_user_untip || $chat_lists_another_untip) {
            //M('privatechat')->where(['touserid' => $user_id])->save(['sound_tip' => 1]);
            // M('chat_lists')->where(['user_id' => $user_id])->save(['user_untip' => 0]);
            // M('chat_lists')->where(['another_id' => $user_id])->save(['another_untip' => 0]);
            $code = 200;
            $message = 1;
        } else {
            $code = 400;
            $message = 0;
        }
         if ($user['sex'] == '男'){
            // $zhaohucount = M()->query("select sum(unread) as count from ((SELECT user_unread as unread FROM chat_lists WHERE user_id = $user_id and user_delete = 0 and another_first = 1) UNION ALL (SELECT another_unread as unread FROM chat_lists WHERE another_id = $user_id and another_delete = 0 and user_first = 1)) as a");
            // if ($zhaohucount  ){
            //     $unread1 =$unread1+ $zhaohucount['0']['count'];
            // }
            
            $zhaohu_user_unread = M('chat_lists')->where(['user_id' => $user_id, 'user_delete' =>0,'another_first'=>1])->sum('user_unread');
            $zhaohu_another_unread = M('chat_lists')->where(['another_id' => $user_id, 'another_delete' =>0,'user_first'=>1])->sum('another_unread');
            $unread1 =$unread1+ $zhaohu_user_unread+$zhaohu_another_unread;
        }
        
        $message = json_encode([
            "code" => $code,
            "action" => 'Home/Privatechat/getreadcount',
            'data' => [
                "message" => $message,
                "chat_count" => (int)$unread1,
                'message_count' => $unread2,
                "privacy_chat_count" => (int)$unread3
            ]
        ]);
        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user['id'], $message);
    }


   public function getreadcountold($data)
    {
        $data = json_decode($data, true);
        $user_id_real = $user_id = $data['user_id'] ?? 6374;
        $res = (new TencentIM)->get_list($user_id);
        if (isset($res['SessionItem']) && !empty($res['SessionItem'])){
            $To_Accounts = array_column($res['SessionItem'], 'To_Account');
            $unreads = (new TencentIM)->get_c2c_unread_msg_num($user_id, $To_Accounts);
            $unread1 =  array_sum($unreads)?? 0;
        }else{
            $unread1 = 0;
        }
        $user = M('user')->field('id, sex, register_datetime, reg, authcode')->cache(true,86400)->where(['id' => $user_id])->find();
        // $sql = "(SELECT sum(user_untip) untip FROM chat_lists WHERE user_id = $user_id_real and user_delete = 0) UNION (SELECT sum(another_untip) untip FROM chat_lists WHERE another_id = $user_id_real and another_delete = 0)";
        // $chat_lists = M()->Query($sql);
        // $untip1 = $chat_lists[0]['untip'] + $chat_lists[1]['untip'];
        
        $chat_lists_user_untip = M('chat_lists')->where(['user_id' => $user_id_real,'user_delete'=>0])->sum('user_untip');
        $chat_lists_another_untip = M('chat_lists')->where(['another_id' => $user_id_real,'another_delete'=>0])->sum('another_untip');
        $untip1 = $chat_lists_user_untip + $chat_lists_another_untip;
    
        $unread3 = 0;
        // $channel = $user['sex'] == '男' ? [1,2] : [1,3];
        // $where = ['channel' => ['in', $channel], 'sys_channel'=>['in', [0,getenv('APP_CHANNEL')]]];
        // $where['_string'] = "(type=0 and (is_top = 1 or create_time >= '" . $user['register_datetime'] . "')) or (to_user=".$user['id']." and type = 32)";
        // $message = M('sys_message')->where($where)->order('is_top desc, id desc')->limit(20)->getField('id', true);
        // if ($message) {
        //     $read_count = M('sys_message_read')->where(['user_id' => $user_id_real, 'message_id' => ['in', $message]])->count();
        //     $unread2 = count($message) - $read_count;
        // } else {
        //     $unread2 = 0;
        // }
          $unread2 =0;
         $sound_tip = $untip1;
        if ($sound_tip) {
            //M('privatechat')->where(['touserid' => $user_id])->save(['sound_tip' => 1]);
            M('chat_lists')->where(['user_id' => $user_id])->save(['user_untip' => 0]);
            M('chat_lists')->where(['another_id' => $user_id])->save(['another_untip' => 0]);
            $code = 200;
            $message = 1;
        } else {
            $code = 400;
            $message = 0;
        }
         if ($user['sex'] == '男'){
            // $zhaohucount = M()->query("select sum(unread) as count from ((SELECT user_unread as unread FROM chat_lists WHERE user_id = $user_id and user_delete = 0 and another_first = 1) UNION ALL (SELECT another_unread as unread FROM chat_lists WHERE another_id = $user_id and another_delete = 0 and user_first = 1)) as a");
            // if ($zhaohucount  ){
            //     $unread1 =$unread1+ $zhaohucount['0']['count'];
            // }
            
            $zhaohu_user_unread = M('chat_lists')->where(['user_id' => $user_id, 'user_delete' =>0,'another_first'=>1])->sum('user_unread');
            $zhaohu_another_unread = M('chat_lists')->where(['another_id' => $user_id, 'another_delete' =>0,'user_first'=>1])->sum('another_unread');
            $unread1 =$unread1+ $zhaohu_user_unread+$zhaohu_another_unread;
        }
        $message = json_encode([
            "code" => $code,
            "action" => 'Home/Privatechat/getreadcount',
            'data' => [
                "message" => $message,
                "chat_count" => (int)$unread1,
                'message_count' => $unread2,
                "privacy_chat_count" => (int)$unread3
            ]
        ]);
        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user['id'], $message);
    }

    public function changeread($user_id, $touserid)
    {
        $touser = M('user')->find($touserid);
        if($touser['reg'] == 2) {
            $touser = M('user')->find($touser['authcode']);
        }
        // M('privatechat')->where(['userid' => $touserid, 'touserid' => $user_id])->save(['isRead' => 1]);

        // 更新会话列表
         D('ChatLists')->changeLists($user_id, $touserid);
        (new TencentIM)->admin_set_msg_read($user_id, $touserid);

        // 清除聊天缓存
        /*S("getMsgList$user_id&$touserid",null);
        S("getMsgList$touserid&$user_id",null);*/

        $message = json_encode(['code' => 200, 'action' => 'Home/Privatechat/changeread', 'data' => ['touserid' => $user_id,'money'=>100]]);

        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touser['id'], $message);
        
    }

    public function changecount($user_id, $touserid)
    {
        /*M('privatechat')->where(['userid' => $touserid, 'touserid' => $user_id])->save(['isCount' => 1]);

        echo '{"code":"200"}';*/
    }




  public function  getChatList(){
      
        $startTime = microtime(true);
        
        $userid = I('userid', 11);
        $touserid = I('touserid', 12);
        $chat_info = file_get_contents('php://input');
        // Log::write('获取用户聊天信息开始了');
        // // Log::write('用户聊天信息：'.json_encode($chat_info,JSON_UNESCAPED_UNICODE));
        //     Log::write('用户聊天信息：'.$chat_info);
        // Log::write('获取用户聊天信息结束了');
       
        $data = [];
        $user_unread_list =[];
        if (!empty($chat_info)){
            parse_str($chat_info, $output);
            $json_str = $output['chat_info'];
            $decoded_json = urldecode($json_str);
            $chat_list = json_decode($decoded_json, true);
            if (!empty($chat_list)){
                $lastTime =time();
                foreach ($chat_list as $key=>$val){
                    $cloudCustomData = json_decode($val['cloudCustomData'],true);
                    $new_chat_info['id'] = $cloudCustomData['id'] ? $cloudCustomData['id'] :0;
                    $new_chat_info['userid'] = $cloudCustomData['userid'];
                    $new_chat_info['touserid'] = $cloudCustomData['touserid'];
                    $new_chat_info['type'] = $cloudCustomData['type'];
                    $new_chat_info['content'] = $cloudCustomData['content'];
                    $new_chat_info['money'] = $cloudCustomData['money'];
                    $new_chat_info['single'] = $cloudCustomData['single'];
                    $new_chat_info['score'] = $cloudCustomData['score'];
                    $new_chat_info['front_id'] = $cloudCustomData['front_id'];
                    $new_chat_info['send_sex'] = $cloudCustomData['send_sex'];
                    $new_chat_info['ip'] = $cloudCustomData['ip'];
                    $new_chat_info['front_id'] = $cloudCustomData['front_id'];
                    $new_chat_info['finish'] = isset($cloudCustomData['finish']) ? $cloudCustomData['finish'] :0 ;
                    $new_chat_info['state'] = isset($cloudCustomData['state']) ? $cloudCustomData['state'] :0 ;
                    $new_chat_info['status'] = isset($cloudCustomData['status']) ? $cloudCustomData['status'] :0 ;
                    $new_chat_info['second'] = $cloudCustomData['second']? $cloudCustomData['second'] :0 ;

                    $new_chat_info['data'] =json_decode($cloudCustomData['data'], true);

                    if ($cloudCustomData['type'] == 1){
                        $new_chat_info['content'] =  $cloudCustomData['content'].'?x-oss-process=image/resize,p_50';
                    }
                    $new_chat_info['addtime'] = date('Y-m-d H:i:s', $val['time']);
                    $new_chat_info['isRead'] = $val['isPeerRead'];

                    $new_chat_info['showtime'] = $lastTime - $val['time'] > 300;
                    $lastTime =$val['time'];
                    $new_chat_info['timestamp'] = $lastTime;

                     $new_chat_info['time'] = '';
                    // $new_chat_info['time'] = timeTodate($val['time']);
                    $new_chat_info['self'] = $cloudCustomData['userid'] == $userid ? 1 : 0;

                    $new_chat_info['is_burn'] = 0;

                    if (in_array($cloudCustomData['type'], [9, 10])) {
                         $lianmaiChat = json_decode($cloudCustomData['data'], true);
                         
                        if (isset($lianmaiChat['status']) && $lianmaiChat['status']) {
                            if (isset($lianmaiChat['start']) && isset($lianmaiChat['end'])) {
                                $chat_time = $lianmaiChat['end'] - $lianmaiChat['start'];
                                $new_chat_info['chat_time'] = changeTime($chat_time);
                            } else {
                                if ($lianmaiChat['second']) {
                                    $new_chat_info['content'] .= changeTime($lianmaiChat['second'] * 60);
                                } else {
                                    $new_chat_info['content'] .= '00:00';
                                }
                            }
                            if (isset($lianmaiChat['payer'])) {
                                $new_chat_info['payer'] = $lianmaiChat['payer'];
                            }
                        } else {
                            $new_chat_info['content'] .= ' 未接通';
                        }
                    }
                    // 添加发送方头像信息
//                    $senderId = $value['From_Account'] == $userid ? $userid : $touserid;
//                    $CloudCustomData['head_portrait'] = $users[$senderId]['head_portrait'];
                    $new_chat_info['head_portrait'] =$val['avatar'];

                    $data[] = $new_chat_info;
                    // if (!$cloudCustomData['isRead'] && !$new_chat_info['self'] && isset($cloudCustomData['MsgKey'])) {
                    //     $user_unread_list[] = [
                    //         "From_Account"=>(string)$userid,
                    //         "To_Account"=>(string)$touserid,
                    //         "MsgKey"=>$cloudCustomData['MsgKey'],
                    //     ];
                    // }
                }
                }
            }


        if (!empty($data)){
            $timestamp = array_column($data, 'timestamp');
            array_multisort($timestamp, SORT_ASC, $data);
        }
        // if (!empty($user_unread_list)){
        //     (new TencentIM)->c2c_msg_read_receipt_unread($touserid, $userid,$user_unread_list);
        // }
        $endTime = microtime(true);
        //记录接口执行日志
        $cost_time = $endTime - $startTime;
        $payload = [
            'datetime'=>date('Y-m-d H:i:s'),
            'start_time' => $startTime,
            'end_time' => $endTime,
            'cost_time' => $cost_time.'秒',
            'method' => 'getChatList',
            'params' => [
                'userid' => $userid,
                'touserid' => $touserid,
            ],
        ];
        file_put_contents(
            "getchatlist.txt",
            json_encode($payload, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) . PHP_EOL,
            FILE_APPEND | LOCK_EX
        );
        exit(getSuccessJson([$data],'查询成功'));
  }


    public function getMsgListV2()
    {
        
        $userid = I('userid', 11);
        $touserid = I('touserid', 12);
        $MaxTime = I('MaxTime') ?: 0;
        $MsgKey = I('LastMsgKey') ?: 0;
        $pagesize = 60;
        
        $redis = new \Redis();
        $redis->connect('127.0.0.1',getenv('REDIS_PORT'));
        $key = 'getMsgListV2:user_id_'.$userid; // 可以根据需要替换为其他标识符
        // $limit = 1; // 每秒最多100次请求
        // $current = $redis->incr($key);
        // if ($current == 1) {
        //     $redis->expire($key, 0.5); // 设置键的过期时间为1秒
        // }
        // if ($current > $limit) {
        //     exit(json_encode(['code' => 400, 'msg' => '请求过于频繁，请稍后再试。']));
        // }
        
         $list = (new TencentIM)->admin_getroammsg($userid, $touserid, $pagesize, $MaxTime, $MsgKey);
      
        $lastTime = time();
        $user_unread_list = [];
        $data = [];
        $updates = [];
        // $users = M('user')->where(['id' => ['in', [$userid, $touserid]]])->getField('id, name, head_100 ,head_portrait, device_id, sex');
        
        
        
        $user1= $redis->get('userinfo_msglist:user_info_'.$userid);
        if ($user1){
            $user1 = json_decode($user1,true);
        }else{
            $user1 = M('user')->where(['id' => (int)$userid])->field('id, name, head_100 ,head_portrait, device_id, sex')->find();
            $redis->set('userinfo_msglist:user_info_'.$userid,json_encode($user1),14400);
        }
        $user2= $redis->get('userinfo_msglist:user_info_'.$touserid);
        if ($user2){
            $user2 = json_decode($user2,true);
        }else{
            $user2 =M('user')->where(['id' => (int)$touserid])->field('id, name, head_100 ,head_portrait, device_id, sex')->find();
            $redis->set('userinfo_msglist:user_info_'.$touserid,json_encode($user2),14420);
        }
        $users[$userid] = $user1;
        $users[$touserid] = $user2;
        
        // $users[$userid] = M('user')->where(['id' => (int)$userid])->field('id, name, head_100 ,head_portrait, device_id, sex')->find();
        // $users[$touserid] = M('user')->where(['id' => (int)$touserid])->field('id, name, head_100 ,head_portrait, device_id, sex')->find();
        $chat_ids = [];
        
        if (isset($list['MsgList']) && !empty($list['MsgList'])){
           foreach ($list['MsgList'] as $value) {
            if ($value['CloudCustomData']) {
                $value['CloudCustomData'] = json_decode($value['CloudCustomData'], true) ?: $value['CloudCustomData'];
            }
            
           if ($value['CloudCustomData']['type'] == 1){
                $value['MsgBody']['0']['MsgContent']['Text'] = $value['MsgBody']['0']['MsgContent']['Text'].'?x-oss-process=image/resize,p_50';
                $value['CloudCustomData']['content'] =  $value['CloudCustomData']['content'].'?x-oss-process=image/resize,p_50';
            }
            $value['CloudCustomData']['addtime'] = date('Y-m-d H:i:s', $value['MsgClientTime']);
            $value['CloudCustomData']['isRead'] = $value['IsPeerRead'];

            $value['CloudCustomData']['showtime'] = $lastTime - $value['MsgClientTime'] > 300;
            $lastTime = $value['MsgClientTime'];
            $value['CloudCustomData']['timestamp'] = $lastTime;

            //$value['CloudCustomData']['time'] = timeTodate($value['MsgClientTime']);
            $value['CloudCustomData']['time'] = '';

            $value['CloudCustomData']['self'] = $value['From_Account'] == $userid ? 1 : 0;
            if (isset($value['RevokerInfo'])) {
                $value['CloudCustomData']['type'] = -1;   
                $value['CloudCustomData']['status'] = 3;   
            }

            $CloudCustomData = $value['CloudCustomData'];
            unset($value['CloudCustomData']);
            $CloudCustomData['CloudData'] = $value;

            $chat_ids[] = $CloudCustomData['id'];

            $CloudCustomData['is_burn'] = 0;
            $CloudCustomData['data'] = json_decode($CloudCustomData['data'], true);

            if (in_array($CloudCustomData['type'], [9, 10])) {
                if (isset($CloudCustomData['data']['status']) && $CloudCustomData['data']['status']) {
                    if (isset($CloudCustomData['data']['start']) && isset($CloudCustomData['data']['end'])) {
                        $chat_time = $CloudCustomData['data']['end'] - $CloudCustomData['data']['start'];
                        $CloudCustomData['chat_time'] = changeTime($chat_time);
                    } else {
                        if ($CloudCustomData['data']['second']) {
                            $CloudCustomData['content'] .= changeTime($CloudCustomData['data']['second'] * 60);
                        } else {
                            $CloudCustomData['content'] .= '00:00';
                        }
                    }
                    if (isset($CloudCustomData['data']['payer'])) {
                        $CloudCustomData['payer'] = $CloudCustomData['data']['payer'];
                    }
                } else {
                    $CloudCustomData['content'] .= ' 未接通';
                }
            }
            // 添加发送方头像信息
            $senderId = $value['From_Account'] == $userid ? $userid : $touserid;
            $CloudCustomData['head_portrait'] = $users[$senderId]['head_portrait'];
            
            $data[] = $CloudCustomData;

            if (!$CloudCustomData['isRead'] && !$CloudCustomData['self']) {
                $updates[] = $CloudCustomData['id'];
                $user_unread_list[] = [
                    "From_Account"=>(string)$userid,
                    "To_Account"=>(string)$touserid,
                    "MsgKey"=>$value['MsgKey'],
                ];
                // (new TencentIM)->c2c_msg_read_receipt($touserid, $userid, $value['MsgKey']);
            }
        }
        }
      if (!empty($user_unread_list)){
          (new TencentIM)->c2c_msg_read_receipt_unread($touserid, $userid,$user_unread_list);
        }
        // $chats = M('privatechat')->where(['id'=>['in', $chat_ids]])->getField('id, single, finish, money, score');
        // $d2 = [];
        // foreach ($data as $value) {
        //     $single = $value['single'] ?? 0;
        //     if (isset($chats[$value['id']])) {
        //         $single = $chats[$value['id']]['single'];
        //     }
        //     if ($value['userid'] == $userid) {
        //         if ($single == 1) {
        //             continue;
        //         }
        //     } else {
        //         if ($single == 2) {
        //             continue;
        //         }
        //     }
        //     $d2[] = $value;
        // }
        // $data = $d2;


        if (sizeof($updates)) {
            
            if (!empty($updates)){
           
            //   if (count($updates) >800){
            //         foreach ($updates as $key=>$val){
            //             M('privatechat')->where(['id' =>$val])->setField('isRead', 1);
            //         }
            //     }else{
            //         M('privatechat')->where(['id' => ['in', $updates]])->setField('isRead', 1);
            //     }
                
                //   foreach ($updates as $key=>$val){
                //         M('privatechat')->where(['id' =>$val])->setField('isRead', 1);
                // }
            }
            // M('privatechat')->where(['id' => ['in', $updates]])->setField('isRead', 1);

            // $config = M('config_system')->where(['category' => ['in', ['kefu']]])->cache(true, 86400)->getField('title, content');
            //   $config = M('config_system')->where(['category' =>'kefu'])->cache(true, 86400)->getField('title, content');
            // if ($userid != $config['id'] && $touserid != $config['id'] && $users[$userid]['sex'] == '男' && $users[$touserid]['sex'] == '女') {
            //     $ids = array_column($data, 'id');
            //     $data_count = count($ids);
            //     if ($data_count == 1 || (isset($data[$data_count - 1]['showtime']) && $data[$data_count - 1]['showtime'])) {
            //         // $contain_tip = ['userid' => $userid, 'touserid' => $touserid, 'type' => -1, 'single' => 1, "content" => '对方查看了你的消息', 'finish' => 1, 'is_public' => 1];
            //         // $msgid = M('privatechat')->add($contain_tip);
            //         // $contain_tip['id'] = $msgid;
            //         // $TencentIMResponse = (new TencentIM)->sendmsg($contain_tip['userid'], $contain_tip['touserid'], $contain_tip['content']??'', $contain_tip, $contain_tip['single']??0);
            //         // $chat_data_o = [];
            //         // $chat_data_o['MsgKey'] = $TencentIMResponse['MsgKey']??'';
            //         // $contain_tip['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
            //         //   M('privatechat')->save($contain_tip);

            //         // 更新会话列表
            //         //   D('ChatLists')->updateLists($userid, $touserid, 1, -1, '对方查看了你的消息');
            //         //   $this->getOtherList(json_encode(['userid' => $touserid, 'count' => '', 'type' => '']));
            //     }
            // }
        }
        //   (new TencentIM)->admin_set_msg_read($userid, $touserid);

        // 清空与对方的消息
        // (new TencentIM)->delete_c2c_msg_ramble($userid, $touserid, array_column($list['MsgList'], 'MsgKey'));

        // echo "<pre>";
        // var_dump($data);
        exit(getSuccessJson([$data]));
    }

    //获取开始的20条信息
    public function getMsgList()
    {
        return $this->getMsgListV2();
        $userid = I('userid');
        $touserid = I('touserid');
        $page = I('page') ?: 0;
        $pages = I('pages') ?: 20;
        $type = I('type') ?? false;
        $where = '';
        if ($type === "0" || $type) {
            $where = ' and type='.$type;
        }

        // $hasCache = S('getMsgList:' . $userid . ':' . $touserid);
        // if ($hasCache) {
        //     exit(json_encode(['code' => 201, 'data' => []]));
        // } else {
        //     S('getMsgList:' . $userid . ':' . $touserid, 1, 1);
        // }

        $start = $page * $pages;
        $unionCount = ($page + 1) * $pages;

        $lastTime = time();

        $Model = M('privatechat');

        $users = M('user')->where(['id' => ['in', [$userid, $touserid]]])->getField('id, name, head_100 ,head_portrait, device_id, sex');

        $whereDev1 = '';
        $whereDev2 = '';
        // $whereDev1 = " and (data like '%\"u_d_id\":\"".$users[$userid]['device_id']."\"%' or data not like '%u_d_id%')";
        // $whereDev2 = " and (data like '%\"t_d_id\":\"".$users[$userid]['device_id']."\"%' or data not like '%t_d_id%')";

        $sql = "(select id, type, userid, content, isRead, is_burn, second, status, state, data, k, score, finish, location,addtime  from privatechat where userid = $userid and touserid = $touserid and single <> 1 and status not in (-1,1,4) $where $whereDev1 order by id desc limit $unionCount) union all (select id, type, userid, content, isRead, is_burn, second, status, state, data, k, score, finish, location,addtime  from privatechat where userid = $touserid and touserid = $userid and single <> 2 and status not in (-1,2,4) $where $whereDev2 order by id desc limit $unionCount) order by id desc limit $start, $pages";

        $data = $Model->Query($sql);

        if ($data) {
            $updates = [];
            $updateAll = [];
            foreach ($data as $key => $item) {
                $data[$key]['isRead'] = $item['isRead'] = (int)$item['isRead'];
                if (!$item['isRead'] && $item['userid'] != $userid) {
                    $updates[] = $item['id'];
                }
                $updateItem = [];
                if ($item['userid'] != $userid && strpos($item['data'], 't_d_id')===false) {
                    $updateItem['id'] = $item['id'];
                    $updateItem['data'] = $item['data'];
                    if ($updateItem['data'] && strpos($updateItem['data'], '{') === 0) {
                        $updateItem['data'] = json_decode($updateItem['data'], true);
                        $updateItem['data']['t_d_id'] = $users[$userid]['device_id'];
                        $updateItem['data'] = json_encode($updateItem['data'], JSON_UNESCAPED_UNICODE);
                    } else {
                        $updateItem['data'] = json_encode(['t_d_id' => $users[$userid]['device_id'], 'value'=>$updateItem['data']??''], JSON_UNESCAPED_UNICODE);
                    }
                    $updateAll[] = $updateItem;
                }

                $data[$key]['name'] = $users[$item['userid']]['name'];
                $data[$key]['head_portrait'] = $users[$item['userid']]['head_portrait'];

                $data[$key]['self'] = $item['userid'] == $userid ? 1 : 0;

                $data[$key]['showtime'] = $lastTime - strtotime($item['addtime']) > 300;
                $lastTime = strtotime($item['addtime']);
                $data[$key]['timestamp'] = $lastTime;

                $data[$key]['time'] = timeTodate(strtotime($item['addtime']));


                $data[$key]['type'] = $item['type'] == -2 ? 0 : $item['type'];

                $datas = json_decode($item['data'], true);
                if (isset($datas['image'])) {
                    $datas['image'] = changeUrl($datas['image']);
                }

                if($item['type'] != 13){
                    $datas['cover'] = $datas['cover'] ?? '';
                }
                $data[$key]['data'] = $datas;

                if (in_array($item['type'], [9, 10])) {
                    if (isset($datas['status']) && $datas['status']) {
                        if (isset($datas['start']) && isset($datas['end'])) {
                            $chat_time = $datas['end'] - $datas['start'];
                            $data[$key]['chat_time'] = changeTime($chat_time);
                        } else {
                            if ($datas['second']) {
                                $data[$key]['content'] .= changeTime($datas['second'] * 60);
                            } else {
                                $data[$key]['content'] .= '00:00';
                            }
                        }
                        if (isset($datas['payer'])) {
                            $data[$key]['payer'] = $datas['payer'];
                        }
                    } else {
                        $data[$key]['content'] .= ' 未接通';
                    }
                } else if ($item['type'] == 11) {
                    $data[$key]['content'] = changeUrl($item['content']);
                }
            }

            $ids = array_column($data, 'id');
            array_multisort($ids,SORT_ASC,$data);


            if (!empty($updateAll)) {
                // print_r($updateAll);exit;
                _db_batch_update('privatechat', $updateAll, 'id');
            }

            if ($updates) {
                $Model->where(['id' => ['in', $updates]])->setField('isRead', 1);


                if ($data) {
                    if ($userid != 5559516 && $touserid != 5559516 && $users[$userid]['sex'] == '男' && $users[$touserid]['sex'] == '女') {
                        $data_count = count($ids);
                        if ($data_count == 1 || (isset($data[$data_count - 1]['showtime']) && $data[$data_count - 1]['showtime'])) {
                            $contain_tip = ['userid' => $userid, 'touserid' => $touserid, 'type' => -1, 'single' => 1, "content" => '对方查看了你的消息', 'finish' => 1, 'is_public' => 1];
                            M('privatechat')->add($contain_tip);
                            // 更新会话列表
                            D('ChatLists')->updateLists($userid, $touserid, 1, -1, '对方查看了你的消息');
                            $this->getOtherList(json_encode(['userid' => $touserid, 'count' => '', 'type' => '']));
                        }
                    }
                }
            }
        }

        // 更新会话列表
        D('ChatLists')->changeLists($userid, $touserid);

        exit(getSuccessJson([$data]));
    }

    public function unreadList()
    {
        $userid = I('userid');
        $touserid = I('touserid');

        $list = M('privatechat')->where(['userid'=>$touserid, 'touserid'=>$userid, 'isRead'=>0])->select();

        foreach ($list as $key => $value) {
            $this->pushNewMsg($value);
        }
    }
    
    //用户绑定客服信息
     public function  bind_customer(){
        $user_id = I('bind_user_id',0);
//        $customer_id=20381353;
        $bindInfo = M('bind_customer')->where(['user_id'=>$user_id,'is_valid'=>1])->field('id,customer_id')->find();
        if ($bindInfo){
            $customer_id = $bindInfo['customer_id'] ;
        }else{
            $arr = customer_info();
            $lastBindInfo =  M('bind_customer')->field('id,customer_id')->where(['is_valid'=>1])->order('id desc')->find();
            if ($lastBindInfo){
                $customer_id =  getNextValue($arr,$lastBindInfo['customer_id']);
            }else{
                $customer_id =6382;
            }
            $newBind = [
                'user_id'=>$user_id,
                'customer_id'=>$customer_id,
                'bind_time'=>time(),
            ];
            M('bind_customer')->add($newBind);
        }
        $data = [
            'customer_id'=>$customer_id
        ];
        exit(json_encode(['code' => 200, 'data' => $data]));
    } 
    

    
    //获取信息列表
    public function getOtherListV2($data)
    {
        $data = json_decode($data, true);

        $userid = $data['userid'] ?? 6374;
        
        // $customer_name =I('customer_name',0);
        // if ($customer_name){
        //     $bind_customer_id = customer_info()[$customer_name];
        //     if ($bind_customer_id){
        //         $userid = $bind_customer_id;
        //     }
        //     //  Log::write('这是客服信息id：'.$bind_customer_id);
        // }
        
        $config = M('config_system')->where(['category' => ['in', ['kefu', 'family', 'user']]])->cache(true, 86400)->getField('title, content');
        $res = (new TencentIM)->get_list($userid);  

        $data = [];
        $dataFormat = [
            "id"=>"20870376",
            "from"=>"1",
            "content"=>"q",
            "userid"=>"11",
            "touserid"=>"11",
            "type"=>"0",
            "count"=>"0",
            "isRead"=>0,
            "sort"=>2739175895,
            "top"=>"1",
            "addtime"=>"2025/02/10",
            "is_cluster"=>0,
            "cluster_types"=>0,
            "noble_circle"=>"",
            "noble_icon"=>"",
            "real_avatar"=>"0",
            "name"=>"伽罗",
            "sex"=>"女",
            "register_datetime"=>"2020-09-07 16=>36=>52",
            "age"=>"32",
            "entertainment"=>"0",
            "entertainment_text"=>"",
            "entertainment_child"=>"",
            "entertainment_child_text"=>"",
            "is_online"=>"0",
            "kefu"=>0,
            "is_identity_authentication"=>"2",
            "sumb_headimg"=>"/disk/uploads/image/20241121/1a69cb4782058b5f15593e54253e1328f6224a52.jpg",
            "city_mask"=>"汕头3",
            "city"=>"",
            "city1"=>"汕头1",
            "intimate"=>0,
        ];

        if (isset($res['SessionItem'])) {
            $apisCommonRedis =apisCommonRedis();
            $To_Accounts = array_column($res['SessionItem'], 'To_Account');
            

            
            $AccountInfos = (new TencentIM)->portrait_gets($To_Accounts);
            $unreads = (new TencentIM)->get_c2c_unread_msg_num($userid, $To_Accounts);
            $this->resetUnread($userid, $unreads);

            // $userInfo = M('user')->where(['id'=>$userid])->field('id, sex, reg')->cache(true,30)->find();
            // if ($userInfo['sex'] == '女') {
            //     $sql = "(SELECT another_id user_id FROM chat_lists WHERE user_id = $userid and user_delete = 0 and user_first = 1) UNION (SELECT user_id FROM chat_lists WHERE another_id = $userid and another_delete = 0 and another_first = 1) $limit";
            // } else {
            //     $sql = "(SELECT another_id user_id FROM chat_lists WHERE user_id = $userid and user_delete = 0 and another_first = 1 ) UNION (SELECT user_id FROM chat_lists WHERE another_id = $userid and another_delete = 0 and user_first = 1) $limit";
            // }
            // $result = M()->Query($sql);
            // $fate_uids = array_column($result, 'user_id');
            // $uids = M('user')->where(['id'=>['in', array_column($res['SessionItem'], 'To_Account')], 'delete_time'=>0])->cache(true,30)->getField('id', true);
            
            // $isHide = M()->query("SELECT is_hide FROM config_personal WHERE user_id = (int)$userid");
            // $isHide = is_null($isHide[0]['is_hide']) ? 0 : $isHide[0]['is_hide'];
            $gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->cache(30)->getField('id, icon, circle');
            $i = 0;
            foreach ($res['SessionItem'] as &$value) {
                //if (in_array($value['To_Account'], $fate_uids)) continue;
                //if (!in_array($value['To_Account'], $uids)) continue;
                if (isset($AccountInfos[$value['To_Account']])) {
                    $value = array_merge($value, $AccountInfos[$value['To_Account']]);
                }

                $item['id'] = $i++;
                $item['content'] = '';
                $item['userid'] = $value['To_Account'];
                $item['touserid'] = $value['To_Account'];
                $item['count'] = $unreads[$value['To_Account']] ?? 0;
                $item['top'] = $value['TopFlag'];
                $item['name'] = $value['Tag_Profile_IM_Nick'];
                $item['sumb_headimg'] = $value['Tag_Profile_IM_Image'];
                $item['sort'] = $item['top']?$value['MsgTime'] + 99999999 : $value['MsgTime'];

                $item['kefu'] = $value['To_Account'] == $config['id'];

                if ($value['MsgTime'] >= strtotime(date('Ymd'))) {
                    $item['addtime'] = date('H:i', $value['MsgTime']);
                } else if ($value['MsgTime'] >= (strtotime(date('Ymd')) - 86400)) {
                    $item['addtime'] = '昨天';
                } else {
                    $item['addtime'] = date('Y/m/d', $value['MsgTime']);
                }
                
                $usernew = $apisCommonRedis->get('user_info:get_user_info_'.$value['To_Account']);
                if ($usernew){
                    $usernew = json_decode($usernew,true);
                }else{
                    $usernew = M('user')->where(['id'=>$value['To_Account']])->field('id, sex,head_portrait, city,delete_time,is_online,is_hide,noble_grade')->find();
                    $apisCommonRedis->set('user_info:get_user_info_'.$value['To_Account'],json_encode($usernew),rand(200,300));
                }
                //  $usernew = M('user')->where(['id'=>$value['To_Account']])->field('id, sex,head_portrait, city,delete_time,is_online,is_hide,noble_grade')->find();
                $item['noble_icon'] = $gradeNoble[$usernew['noble_grade']] ? $gradeNoble[$usernew['noble_grade']]['icon'] :'';//vip头像
                $item['sex2']=$usernew['sex']; //替换错误数据
                $item['city2']=$usernew['city']; //替换错误数据 
                $item['head_portrait']=$usernew['head_portrait']; //不使用缓存中的头像
                $item['delete_time']=$usernew['delete_time']; //>0表示账户已注销
                $item['is_online']=$usernew['is_online']; //是否在线
               // $item['is_online']=$apisCommonRedis->get('user_online:user_is_online_'.$value['To_Account']) ? $apisCommonRedis->get('user_online:user_is_online_'.$value['To_Account']) : 0; //是否在线
                $item['is_hide']=$usernew['is_hide']; //是否隐藏在线状态
                $item = array_merge($dataFormat, $item);

                $data[$value['To_Account']] = $item;
            }
            // $chat_lists = M()->Query("(SELECT another_id touserid, user_content content FROM chat_lists WHERE user_id = $userid) UNION (SELECT user_id touserid, another_content content FROM chat_lists WHERE another_id = $userid)");
            
            
            $chat_list1 = M('chat_lists')->where(['user_id' => (int)$userid])->field('another_id touserid, user_content content')->select();
            $chat_list2 = M('chat_lists')->where(['another_id' => (int)$userid])->field('user_id touserid, another_content content')->select();
            $chat_lists = array_merge($chat_list1,$chat_list2);

            foreach ($chat_lists as $key => $value) {
                if (isset($data[$value['touserid']])) {
                    $data[$value['touserid']]['content'] = $value['content'];
                }
            }
            $data = array_values($data);
            array_multisort(array_column($data,'sort'),SORT_DESC,$data);
        }
        // echo "<pre>";
        // var_dump($data);exit;
        // var_dump(getenv('SOCKET_PREFIX') . $userid);exit;
        $data = json_encode(['code' => 200, 'action' => 'Home/Privatechat/getOtherList', 'data' => ['result' => $data, 'count' => 0, 'user_id'=>$userid]]);
        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid, $data);
    }
    public function resetUnread($userid = 0, $unreads = [])
    {
        // foreach ($unreads as $key => $value) {
        //     $where = $userid < $key ? ['user_id'=>$userid, 'another_id'=>$key] : ['user_id'=>$key, 'another_id'=>$userid];

        //     M('chat_lists')->where($where)->setField($userid < $key ? 'user_unread' : 'another_unread', $value);
        // }

        // M('chat_lists')->where([['user_id'=>['not in', array_keys($unreads)], 'another_id'=>$userid], ['user_id'=>$userid, 'another_id'=>['not in', array_keys($unreads)]], '_logic' => 'OR'])->delete();


        // $this->getreadcount(json_encode(['user_id' => $userid]));
    }

    //获取信息列表
    public function getOtherList($data)
    {
        // file_put_contents('1.txt', json_encode($data), FILE_APPEND);
        return $this->getOtherListV2($data);
        $data = json_decode($data, true);

        $userid = $data['userid'];
        $oldcount = $data['count'] ?? '';
        $type = $data['type'] ?? '';
        $friend = $data['friend'] ?? 0;

        $chat_lists_records = M('chat_lists_records')->where(['user_id' => $userid])->find();

        if ($chat_lists_records) {
            $result = $this->chatList($userid);

            $data = json_encode(['code' => 200, 'action' => 'Home/Privatechat/getOtherList', 'data' => ['result' => $result, 'count' => 0, 'user_id'=>$userid]]);
        } else {
            $isfan = false;

            $Model = M();

            $allcount = 0;

            $config = M('config_system')->where(['category' => ['in', ['kefu', 'family', 'user']]])->cache(true, 86400)->getField('title, content');

            $user = M('user')->field('sex')->where(['id' => $userid])->find();
            if ($user['sex'] == '女' && $userid != $config['id']) {
                $unread_uid = M('privatechat')->where(['type' => ['neq', -1], 'single' => ['neq', 1], 'userid' => $userid, 'isRead' => 0, 'is_fate' => 1])->getField('touserid', true);
                $map['_string'] = '(type <> -1 or is_public = 1) and (single <> 1 or is_public = 1)';
                $map['userid'] = ['in', $unread_uid];
                $map['touserid'] = $userid;
                $chat_uid = M('privatechat')->where($map)->getField('userid', true);
                $chat_uid = $chat_uid ?: [];
                $not_reply = implode(',', array_diff($unread_uid, $chat_uid)) ?: 0;

                $sql = "(SELECT userid, MAX(id) AS id FROM privatechat WHERE (type <> -1 or is_public = 1) and userid not in ($not_reply) and touserid = $userid and status <> -1 GROUP BY userid) UNION (SELECT touserid,MAX(id) AS id FROM privatechat WHERE (type <> -1 or is_public = 1) and single <> 1 and userid = $userid and touserid not in ($not_reply) and status <> -1 GROUP BY touserid)";

            } else {
                $sql = "(SELECT userid, MAX(id) AS id FROM privatechat WHERE (type <> -1 or is_public = 1) and touserid = $userid and status <> -1 GROUP BY userid) UNION (SELECT touserid,MAX(id) AS id FROM privatechat WHERE (type <> -1 or is_public = 1) and single <> 1 and userid = $userid and status <> -1 GROUP BY touserid)";
            }

            $result = $Model->Query($sql);



            // 家族
            $gresult = [];
            if (intval($config['family_switch'])) {
                $sql = "select t.*, t1.name, t1.logo sumb_headimg from cluster_user t, cluster t1 where t.user_id = $userid and t1.types = 1 and t.status = 1 and t1.id = t.cluster_id";
                $glist = $Model->Query($sql);

                $cluster_ids = array_column($glist, 'cluster_id');

                $clusterChats = M('clusterchat')->where(['cluster_id' => ['in', $cluster_ids]])->getField('cluster_id, id, type, content, addtime');
                $talkcounts = M('clusterchat')->where(['cluster_id' => ['in', $cluster_ids]])->group('cluster_id')->getField('cluster_id, count(*) count');

                for ($i = 0; $i < sizeof($glist); $i++) {
                    $talkcount = $talkcounts[$glist[$i]['cluster_id']] ?? 0;

                    if ($talkcount > 0) {
                        $glist[$i]['is_cluster'] = 1;
                        $glist[$i]['cluster_types'] = 1;

                        $talkone = $clusterChats[$glist[$i]['cluster_id']];

                        $glist[$i]['kefu'] = 0;
                        $glist[$i]['id'] = $talkone['id'];
                        $glist[$i]['touserid'] = $talkone['cluster_id'];
                        $glist[$i]['content'] = $talkone['content'];
                        $glist[$i]['sort_field'] = strtotime($talkone['addtime']);
                        $glist[$i]['addtime'] = time_tran($talkone['addtime']);

                        $count2 = $Model->Query("select count(*) as count from clusterchat where cluster_id=" . $glist[$i]['cluster_id'] . " and find_in_set($userid, isRead)");

                        $count = $talkcount - $count2[0]['count'];

                        if ($count > 0) {
                            $isfan = true;
                        }
                        $allcount = $allcount + $count;
                        $glist[$i]['count'] = $count;

                        $channel = [1 => '[图片]', 2 => '[语音]', 3 => '[视频]', 6 => '[位置]', 8 => '[礼物]', 11 => '[表情]'];

                        if (isset($channel[$talkone['type']])) {
                            $glist[$i]['content'] = $channel[$talkone['type']];
                        }

                        array_push($gresult, $glist[$i]);
                    }
                }
            }


            $kefu = intval($config['id']);

            $ids = array_column($result, 'id');
            $uids = array_column($result, 'userid');
            $chats = M('privatechat')->where(['id' => ['in', $ids]])->cache(true, 86400)->getField('id, content, userid, touserid, status, state, type, isRead, addtime');
            $users = M('user')->where(['id' => ['in', $uids], 'delete_time' => 0])->getField('id, head_100, name, sex, age, city, is_identity_authentication, noble_grade, noble_time, is_online, real_avatar, register_datetime, entertainment,entertainment_child');
            //$personals = M('config_personal')->where(['user_id' => ['in', $uids]])->getField('user_id, hide_distance, id');
            $delChat = M('del_chat')->where(['uid' => $userid])->getField('to_uid', true);
            //$gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->cache(true, 86400)->getField('id, icon, circle');
            $gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->cache(30)->getField('id, icon, circle');
            $userIds = [];
            foreach ($result as $k => $v) {
                $userIds[] = $v['userid'] == $userid ? $v['touserid'] : $v['userid'];
            }

            $map['_string'] = 'type <> -1 or is_public = 1';
            $map['userid'] = ['in', $userIds];
            $map['touserid'] = $userid;
            $map['status'] = ['not in', [-1,2]];
            $map['isRead'] = 0;
            $counts = M('privatechat')
                //->where(['type' => ['neq', -1], 'userid' => ['in', $userIds], 'touserid' => $userid, 'status' => ['not in', [-1,2]], 'isRead' => 0])
                ->where($map)
                ->group('userid, touserid')
                ->getField('CONCAT_WS("+", userid, touserid), COUNT(*) AS count');

            $del = [];

            $roles = M('user_entertainment')->getField('id, name');
            foreach ($result as $k => $v) {
                if (in_array($v['userid'], $delChat)) {
                    unset($result[$k]);
                } else {
                    if (isset($users[$v['userid']]) && isset($chats[$v['id']])) {
                        /*if ($userid == $kefu && $users[$v['userid']]['sex'] == '男') {
                            unset($result[$k]);
                            continue;
                        }*/

                        $chat = $chats[$v['id']];
                        $user = $users[$v['userid']];

                        $sql = $userid == $chat['userid'] ? ' and single <> 1 ' : '';

                        if ($v['userid'] == $userid) {
                            $count = $counts[$v['touserid'] . '+' . $userid]['count'] ?? 0;
                        } else {
                            $count = $counts[$v['userid'] . '+' . $userid]['count'] ?? 0;
                        }

                        $result[$k]['content'] = $chat['content'];
                        $result[$k]['touserid'] = $chat['touserid'];
                        $result[$k]['status'] = $chat['status'];
                        $result[$k]['state'] = $chat['state'];
                        $result[$k]['type'] = $chat['type'];
                        $result[$k]['sort_field'] = strtotime($chat['addtime']);
                        //$result[$k]['addtime'] = strtotime($chat['addtime']) >= strtotime(date('Ymd')) ? date('H:i', strtotime($chat['addtime'])) : $chat['addtime'];

                        if (strtotime($chat['addtime']) >= strtotime(date('Ymd'))) {
                            $result[$k]['addtime'] = date('H:i', strtotime($chat['addtime']));
                        } else if (strtotime($chat['addtime']) >= (strtotime(date('Ymd')) - 86400)) {
                            $result[$k]['addtime'] = '昨天';
                        } else {
                            $result[$k]['addtime'] = date('Y/m/d', strtotime($chat['addtime']));
                        }
                        $result[$k]['name'] = $user['name'];
                        $result[$k]['sex'] = $user['sex'];
                        $result[$k]['register_datetime'] = $user['register_datetime'];
                        $result[$k]['age'] = $user['age'];
                        $result[$k]['entertainment'] = $user['entertainment'] ?? 0;
                        $result[$k]['entertainment_text'] = $roles[$user['entertainment']+1] ?? 0;
                        $result[$k]['entertainment_child'] = $user['entertainment_child'] ?? 0;
                        $result[$k]['entertainment_child_text'] = $user['entertainment_child'] ? getRoles($user['entertainment_child'], $roles) : '';
                        $result[$k]['real_avatar'] = $user['real_avatar'];
                        $result[$k]['is_online'] = $user['is_online'];
                        // $result[$k]['is_online'] = 0;

                        /*if (isset($personals[$v['userid']]['hide_distance']) && $personals[$v['userid']]['hide_distance']) {
                            $result[$k]['city'] = '';
                        } else {
                            $result[$k]['city'] = $user['city'];
                        }

                        if ($config['hide_city'] && $user['sex'] == '女') {
                            $result[$k]['city'] = '';
                        }*/

                        $result[$k]['city'] = '';

                        if ($user['noble_grade'] && $user['noble_time'] > time()) {
                            $result[$k]['noble_circle'] = $gradeNoble[$user['noble_grade']] ? $gradeNoble[$user['noble_grade']]['circle'] : '';
                        } else {
                            $result[$k]['noble_circle'] = '';
                        }

                        $result[$k]['kefu'] = $user['id'] == $kefu ? 1 : 0;
                        $result[$k]['is_identity_authentication'] = $user['is_identity_authentication'];
                        $result[$k]['sumb_headimg'] = $user['head_100'];
                        $result[$k]['count'] = $count;
                        $result[$k]['isRead'] = $chat['isRead'];
                        $result[$k]['is_cluster'] = 0;
                        $result[$k]['cluster_types'] = 0;


                        if ($user['noble_grade'] && $user['noble_time'] > time()) {
                            $result[$k]['noble_icon'] = $gradeNoble[$user['noble_grade']] ?? '';
                        } else {
                            $result[$k]['noble_icon'] = '';
                        }

                        $allcount = $allcount + $count;

                        $channel = [1 => '[图片]', 2 => '[语音]', 3 => '[视频]', 6 => '[位置]', 8 => '[礼物]', 11 => '[表情]'];

                        if (isset($channel[$result[$k]['type']])) {
                            $result[$k]['content'] = $channel[$result[$k]['type']];

                            if ($result[$k]['type'] == 11) {
                                $result[$k]['content'] = changeUrl($result[$k]['content']);
                            }
                        } else if ($result[$k]['type'] == -1) {
                            switch ($result[$k]['status']) {
                                case 0:
                                    if ($result[$k]['state'] == 1) {
                                        if ($chat['userid'] != $userid) {
                                            $name = M('user')->where(['id' => $chat['userid']])->getField('name');
                                            $result[$k]['content'] = '"' . $name . '"领取了你的红包';
                                        } else {
                                            $name = M('user')->where(['id' => $chat['touserid']])->getField('name');
                                            $result[$k]['content'] = '你已领取"' . $name . '"的红包';
                                        }
                                    }
                                    break;
                                case 3:
                                    if ($chat['userid'] == $userid) {
                                        $result[$k]['content'] = '你撤回了一条消息';
                                    } else {
                                        $name = M('user')->where(['id' => $chat['userid']])->getField('name');
                                        $result[$k]['content'] = '"' . $name . '"撤回了一条消息';
                                    }
                                    break;
                            }
                        } else {
                            if ($result[$k]['single']) {
                                if ($user[0]['sex'] == '男') {
                                    $result[$k]['content'] = '[回复消息得奖励]';
                                }
                            } else {
                                if (in_array($result[$k]['type'], [5, 7]) && in_array($result[$k]['state'], [0, 2])) {
                                    $result[$k]['content'] = '[红包]' . $result[$k]['content'];
                                }
                                switch ($result[$k]['status']) {
                                    case 1:
                                        if ($chat['userid'] == $userid) {
                                            $result[$k]['content'] = '[消息已删除]';
                                        }
                                        break;
                                    case 2:
                                        if ($chat['touserid'] == $userid) {
                                            $result[$k]['content'] = '[消息已删除]';
                                        }
                                        break;
                                    default :
                                        break;
                                }
                            }
                        }
                    } else {
                        unset($result[$k]);

                        $del[] = $v['userid'];
                    }
                }
            }

            if ($del) {
                //M('privatechat')->where(['userid|touserid' => ['in', $del]])->delete();
            }

            if ($type == 0 || $allcount != $oldcount) {
                $result = array_merge($result, $gresult);

                // 去除重复项，将最新聊天顶上去
                if ($result) {
                    array_multisort(array_column($result, 'sort_field'), SORT_DESC, $result);

                    $con = [];
                    $arr = [];
                    foreach ($result as $k => $v) {
                        if (!in_array($v['userid'], $arr)) {
                            $con[$k] = $v;
                            $arr[$k] = $v['userid'];

                            $con[$k]['top'] = 0;
                            $con[$k]['sort'] = 0;
                        }
                    }
                    $result = array_values($con);

                    $tops_chat = M('top_chat')->where(['types' => 1, 'uid' => $userid])->order('id asc')->getField('to_uid', true);
                    //$tops_cluster = M('top_chat')->where(['types' => 2, 'uid' => $userid])->order('id asc')->getField('to_uid', true);
                    $tops_cluster = [];

                    if ($tops_chat || $tops_cluster) {
                        $con1 = [];
                        $con2 = [];
                        foreach ($result as $k => $v) {

                            $tops = $v['is_cluster'] ? $tops_cluster : $tops_chat;

                            if ($v['is_cluster']) {
                                $tops = $tops_cluster;
                                $tops_field = 'cluster_id';
                            } else {
                                $tops = $tops_chat;
                                $tops_field = 'userid';
                            }

                            if (in_array($v[$tops_field], $tops)) {
                                $v['top'] = 1;
                                $v['sort'] = array_search($v[$tops_field], $tops);
                                $con1[] = $v;
                            } else {
                                $con2[] = $v;
                            }
                        }

                        if ($con1) {
                            $tmp = array_column($con1, 'sort');
                            array_multisort($tmp, SORT_DESC, $con1);
                        }

                        $result = array_merge($con1, $con2);
                    }
                }

                //array_multisort(array_column($result, 'addtime'), SORT_DESC, $result);

                if ($userid != $kefu) {
                    $kefus = [];
                    $contain1 = [];
                    $contain2 = [];
                    foreach ($result as $key => $item) {
                        if ($item['kefu']) {
                            $item['city'] = '';
                            $kefus[] = $item;
                        } else if (!$item['is_cluster'] && $item['touserid'] == $kefu) {
                            $contain1[] = $item;
                        } else {
                            $contain2[] = $item;
                        }
                    }

                    $result = array_merge($kefus, $contain1, $contain2);
                }

                foreach ($result as $key => $item) {
                    /*$intimate = M('user_intimate')->where(['couple_a|couple_b' => $item['touserid'] . ',' . $userid, 'intimate' => ['gt', 0]])->getField('intimate');

                    $result[$key]['intimate'] = $intimate ?: 0;*/

                    $result[$key]['intimate'] = 0;
                }

                $data = json_encode(['code' => 200, 'action' => 'Home/Privatechat/getOtherList', 'data' => ['result' => $result, 'count' => $allcount, 'user_id'=>$userid]]);
            } else {
                $data = json_encode(['code' => 400, 'action' => 'Home/Privatechat/getOtherList', 'data' => []]);
            }

            // 更新会话列表
            D('ChatLists')->synchLists($userid, $result);
        }

        $userInfo = M('user')->find($userid);
        if ($userInfo['reg']==2) {
            $userid = $userInfo['authcode'];
        }
        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid, $data);
    }

    // 未回复列表
    public function notReplyList($data='', $userid, $page=1)
    {
        $data = json_decode($data, true);

        $oldcount = $data['count'] ?? '';
        $type = $data['type'] ?? '';
        $friend = $data['friend'] ?? 0;

        $isfan = false;

        $Model = M();

        $allcount = 0;

        // $page = ($page - 1) * 10;

        $result = $this->chatList($userid, 1, $page);

        exit(json_encode(['code' => 200, 'data' => $result]));

    
        $unread_uid = M('privatechat')->where(['type' => ['neq', -1], 'single' => ['neq', 1], 'userid' => $userid, 'isRead' => 0, 'is_fate' => 1])->getField('touserid', true);
        $map['_string'] = '(type <> -1 or is_public = 1) and (single <> 1 or is_public = 1)';
        $map['userid'] = ['in', $unread_uid];
        $map['touserid'] = $userid;
        $chat_uid = M('privatechat')->where($map)->getField('userid', true);
        $chat_uid = $chat_uid ?: [];
        $not_reply = implode(',', array_diff($unread_uid, $chat_uid)) ?: 0;

        $sql = "(SELECT userid, MAX(id) AS id FROM privatechat WHERE type <> -1 and userid in ($not_reply) and touserid = $userid and status <> -1 GROUP BY userid) UNION (SELECT touserid,MAX(id) AS id FROM privatechat WHERE type <> -1 and single <> 1 and userid = $userid and touserid in ($not_reply) and status <> -1 GROUP BY touserid) LIMIT $page,10";
        $result = $Model->Query($sql);

        $config = M('config_system')->where(['category' => ['in', ['kefu', 'family', 'user']]])->getField('title, content');

        // 家族
        $gresult = [];

        $kefu = intval($config['id']);

        $ids = array_column($result, 'id');
        $uids = array_column($result, 'userid');
        $chats = M('privatechat')->where(['id' => ['in', $ids]])->getField('id, content, userid, touserid, status, state, type, isRead, addtime');
        $users = M('user')->where(['id' => ['in', $uids]])->getField('id, head_100, name, sex, age, city, is_identity_authentication, noble_grade, noble_time, entertainment,delete_time,is_online,is_hide');
        $delChat = M('del_chat')->where(['uid' => $userid])->getField('to_uid', true);
        //$gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->cache(86400)->getField('id, icon, circle');
        $gradeNoble = M('grade_noble')->where(['id' => ['gt', 0]])->cache(30)->getField('id, icon, circle');
        $userIds = [];
        foreach ($result as $k => $v) {
            $userIds[] = $v['userid'] == $userid ? $v['touserid'] : $v['userid'];
        }

        $counts = M('privatechat')
            ->where(['type' => ['neq', -1], 'userid' => ['in', $userIds], 'touserid' => $userid, 'status' => ['not in', [-1,2]], 'isRead' => 0])
            ->group('userid, touserid')
            ->getField('CONCAT_WS("+", userid, touserid), COUNT(*) AS count');

        $del = [];
        foreach ($result as $k => $v) {
            if (in_array($v['userid'], $delChat)) {
                unset($result[$k]);
            } else {
                if (isset($users[$v['userid']]) && isset($chats[$v['id']])) {
                    $chat = $chats[$v['id']];
                    $user = $users[$v['userid']];

                    $sql = $userid == $chat['userid'] ? ' and single <> 1 ' : '';

                    if ($v['userid'] == $userid) {
                        $count = $counts[$v['touserid'] . '+' . $userid]['count'] ?? 0;
                    } else {
                        $count = $counts[$v['userid'] . '+' . $userid]['count'] ?? 0;
                    }

                    $result[$k]['content'] = $chat['content'];
                    $result[$k]['touserid'] = $chat['touserid'];
                    $result[$k]['status'] = $chat['status'];
                    $result[$k]['state'] = $chat['state'];
                    $result[$k]['type'] = $chat['type'];
                    $result[$k]['sort_field'] = strtotime($chat['addtime']);
                    //$result[$k]['addtime'] = strtotime($chat['addtime']) >= strtotime(date('Ymd')) ? date('H:i', strtotime($chat['addtime'])) : $chat['addtime'];

                    if (strtotime($chat['addtime']) >= strtotime(date('Ymd'))) {
                        $result[$k]['addtime'] = date('H:i', strtotime($chat['addtime']));
                    } else if (strtotime($chat['addtime']) >= (strtotime(date('Ymd')) - 86400)) {
                        $result[$k]['addtime'] = '昨天';
                    } else {
                        $result[$k]['addtime'] = date('Y/m/d', strtotime($chat['addtime']));
                    }
                    $result[$k]['name'] = $user['name'];
                    $result[$k]['sex'] = $user['sex'];
                    $result[$k]['age'] = $user['age'];
                    $result[$k]['entertainment'] = $user['entertainment'];
                    
                    $result[$k]['delete_time'] = $user['delete_time'];  // 用户删除状态
                    $result[$k]['is_online'] = $user['is_online'];    // 用户在线状态
                    $result[$k]['is_hide'] = $user['is_hide'];      // 用户隐私设置

                    /*if (isset($personals[$v['userid']]['hide_distance']) && $personals[$v['userid']]['hide_distance']) {
                        $result[$k]['city'] = '';
                    } else {
                        $result[$k]['city'] = $user['city'];
                    }

                    if ($config['hide_city'] && $user['sex'] == '女') {
                        $result[$k]['city'] = '';
                    }*/

                    $result[$k]['city'] = '';

                    if ($user['noble_grade'] && $user['noble_time'] > time()) {
                        $result[$k]['noble_circle'] = $gradeNoble[$user['noble_grade']] ? $gradeNoble[$user['noble_grade']]['circle'] : '';
                    } else {
                        $result[$k]['noble_circle'] = '';
                    }

                    $result[$k]['kefu'] = $user['id'] == $kefu ? 1 : 0;
                    $result[$k]['is_identity_authentication'] = $user['is_identity_authentication'];
                    $result[$k]['sumb_headimg'] = $user['head_100'];
                    $result[$k]['count'] = $count;
                    $result[$k]['isRead'] = $chat['isRead'];
                    $result[$k]['is_cluster'] = 0;
                    $result[$k]['cluster_types'] = 0;


                    if ($user['noble_grade'] && $user['noble_time'] > time()) {
                        $result[$k]['noble_icon'] = $gradeNoble[$user['noble_grade']] ?? '';
                    } else {
                        $result[$k]['noble_icon'] = '';
                    }

                    $allcount = $allcount + $count;

                    $channel = [1 => '[图片]', 2 => '[语音]', 3 => '[视频]', 6 => '[位置]', 8 => '[礼物]', 11 => '[表情]'];

                    if (isset($channel[$result[$k]['type']])) {
                        $result[$k]['content'] = $channel[$result[$k]['type']];

                        if ($result[$k]['type'] == 11) {
                            $result[$k]['content'] = changeUrl($result[$k]['content']);
                        }
                    } else if ($result[$k]['type'] == -1) {
                        switch ($result[$k]['status']) {
                            case 0:
                                if ($result[$k]['state'] == 1) {
                                    if ($chat['userid'] != $userid) {
                                        $name = M('user')->where(['id' => $chat['userid']])->getField('name');
                                        $result[$k]['content'] = '"' . $name . '"领取了你的红包';
                                    } else {
                                        $name = M('user')->where(['id' => $chat['touserid']])->getField('name');
                                        $result[$k]['content'] = '你已领取"' . $name . '"的红包';
                                    }
                                }
                                break;
                            case 3:
                                if ($chat['userid'] == $userid) {
                                    $result[$k]['content'] = '你撤回了一条消息';
                                } else {
                                    $name = M('user')->where(['id' => $chat['userid']])->getField('name');
                                    $result[$k]['content'] = '"' . $name . '"撤回了一条消息';
                                }
                                break;
                        }
                    } else {
                        if ($result[$k]['single']) {
                            if ($user[0]['sex'] == '男') {
                                $result[$k]['content'] = '[回复消息得奖励]';
                            }
                        } else {
                            if (in_array($result[$k]['type'], [5, 7]) && in_array($result[$k]['state'], [0, 2])) {
                                $result[$k]['content'] = '[红包]' . $result[$k]['content'];
                            }
                            switch ($result[$k]['status']) {
                                case 1:
                                    if ($chat['userid'] == $userid) {
                                        $result[$k]['content'] = '[消息已删除]';
                                    }
                                    break;
                                case 2:
                                    if ($chat['touserid'] == $userid) {
                                        $result[$k]['content'] = '[消息已删除]';
                                    }
                                    break;
                                default :
                                    break;
                            }
                        }
                    }
                } else {
                    unset($result[$k]);

                    $del[] = $v['userid'];
                }
            }
        }

        if ($del) {
            //M('privatechat')->where(['userid|touserid' => ['in', $del]])->delete();
        }

        if ($type == 0 || $allcount != $oldcount) {
            $result = array_merge($result, $gresult);

            // 去除重复项，将最新聊天顶上去
            if ($result) {
                array_multisort(array_column($result, 'sort_field'), SORT_DESC, $result);

                $con = [];
                $arr = [];
                foreach ($result as $k => $v) {
                    if (!in_array($v['userid'], $arr)) {
                        $con[$k] = $v;
                        $arr[$k] = $v['userid'];

                        $con[$k]['top'] = 0;
                        $con[$k]['sort'] = 0;
                    }
                }
                $result = array_values($con);

                $tops_chat = M('top_chat')->where(['types' => 1, 'uid' => $userid])->order('id asc')->getField('to_uid', true);
                $tops_cluster = M('top_chat')->where(['types' => 2, 'uid' => $userid])->order('id asc')->getField('to_uid', true);

                if ($tops_chat || $tops_cluster) {
                    $con1 = [];
                    $con2 = [];
                    foreach ($result as $k => $v) {

                        $tops = $v['is_cluster'] ? $tops_cluster : $tops_chat;

                        if ($v['is_cluster']) {
                            $tops = $tops_cluster;
                            $tops_field = 'cluster_id';
                        } else {
                            $tops = $tops_chat;
                            $tops_field = 'userid';
                        }

                        if (in_array($v[$tops_field], $tops)) {
                            $v['top'] = 1;
                            $v['sort'] = array_search($v[$tops_field], $tops);
                            $con1[] = $v;
                        } else {
                            $con2[] = $v;
                        }
                    }

                    if ($con1) {
                        $tmp = array_column($con1, 'sort');
                        array_multisort($tmp, SORT_DESC, $con1);
                    }

                    $result = array_merge($con1, $con2);
                }
            }

            //array_multisort(array_column($result, 'addtime'), SORT_DESC, $result);

            if ($userid != $kefu) {
                $kefus = [];
                $contain1 = [];
                $contain2 = [];
                foreach ($result as $key => $item) {
                    if ($item['kefu']) {
                        $item['city'] = '';
                        $kefus[] = $item;
                    } else if (!$item['is_cluster'] && $item['touserid'] == $kefu) {
                        $contain1[] = $item;
                    } else {
                        $contain2[] = $item;
                    }
                }

                $result = array_merge($kefus, $contain1, $contain2);
            }

            foreach ($result as $key => $item) {
                /*$intimate = M('user_intimate')->where(['couple_a|couple_b' => $item['touserid'] . ',' . $userid, 'intimate' => ['gt', 0]])->getField('intimate');

                $result[$key]['intimate'] = $intimate ?: 0;*/

                $result[$key]['intimate'] = 0;
            }

            $data = json_encode(['code' => 200, 'data' => $result]);
        } else {
            $data = json_encode(['code' => 200, 'data' => []]);
        }

        exit($data);
    }

    // 发送信息
    public function addTalk($userid, $touserid, $type=0, $content='', $second=0, $data='', $timing=0, $greet=0, $system_greet=0, $login_greet=0, $single=0, $fate=0, $notice=0, $quality=0, $return = 0, $front_id = '', $is_public = 0)
    {
        $ispayer = I('ispayer', 0);

        // $redis = new \Redis();
        // $redis->connect('127.0.0.1',getenv('REDIS_PORT'));
        // $key = 'addTalk:user_id_to_touserid'.$userid; // 可以根据需要替换为其他标识符
        // $limit = 1; // 每秒最多100次请求
        // $current = $redis->incr($key);
        // if ($current == 1) {
        //     $redis->expire($key, 1); // 设置键的过期时间为1秒
        // }
        // if ($current > $limit) {
        //     exit(json_encode(['code' => 400, 'msg' => '请求过于频繁，请稍后再试。']));
        // }
           
           
           
        if ($type != 3) {
            
            $timenow = time();
            $isWarnWord = 0;

            $pushNewMsgs = [];

            $content = strip_tags($content);
            
            // if ($type ==1){
            //     $content = $content.'?x-oss-process=image/resize,p_50';
            // }
            $is_burn = I('is_burn') ?: 0;
            $config = M('config_system')->where(['category' => ['in', ['kefu', 'chat', 'greet', 'speaker', 'defend', 'welfare', 'two_way_charge']]])->getField('title, content');
            $kefu = intval($config['id']);

            $blacklist = M('blacklist')->where(['user_id' => $touserid, 'to_user' => $userid])->find();
            if ($blacklist) {
                exit(json_encode(['code' => 400, 'msg' => '对方已把你拉黑，可点击TA的头像，进入用户中心，申请解除拉黑']));
            }
            $blacklist = M('blacklist')->where(['to_user' => $touserid, 'user_id' => $userid])->find();
            if ($blacklist) {
                exit(json_encode(['code' => 400, 'msg' => '你已经把对方拉黑，无法发送信息']));
            }

            $userInfo_privacy = $userInfo = M('user')->master(true)->where(['id' => $userid])->find();
            $touserInfo_privacy = $touserInfo = M('user')->master(true)->where(['id' => $touserid])->find();
            if ($userInfo['reg'] && $userInfo['id'] != $kefu && $userInfo['reg'] != $touserInfo['reg']) {
                exit(json_encode(['code' => 400, 'msg' => '用户类型异常']));
            }
            //如果对方被封号也不能发消息
            if ($touserInfo['is_banned']) {
                exit(json_encode(['code' => 400, 'msg' => '对方账号已被冻结']));
            }
            
            //被限制社交 只能和客服聊天 不能和其他用户发消息 能接收 首页也不能被检索到
            $limit_chat = M('limit_chat')->where(['user_id'=>$userid])->find();
            // if ($limit_chat) {
            //     exit(json_encode(['code' => 400, 'msg' => '你已被禁言']));
            // }
            if ($limit_chat) {
                // 允许和客服聊天
                if ($touserid==$kefu) {
                    // 允许的用户关系，继续执行
                } else {
                    exit(json_encode(['code' => 400, 'msg' => '你已被禁言']));
                }
            }
            
           if ($userInfo_privacy['sex'] == '女') {
                if ($userInfo_privacy['realname_auth'] != 2) {
                    exit(json_encode(['code' => 400, 'msg' => '未实名认证']));
                }
                if (strtotime($userInfo_privacy['register_datetime']) >=1749787200 &&  $userInfo_privacy['is_identity_authentication'] != 2) {
                    exit(json_encode(['code' => 400, 'msg' => '未真人认证']));
                }
            }

            $userid_privacy = $userid;
            $touserid_privacy = $touserid;
            $privacyChat = false;
            // if ($userInfo['reg'] == 2) {
            //     $userInfo_privacy = $userInfo;
            //     $touserInfo_privacy = $touserInfo;
            //     $userInfo = M('user')->master(true)->where(['id' => $userInfo_privacy['authcode'], 'reg'=>1])->find();
            //     $touserInfo = M('user')->master(true)->where(['id' => $touserInfo_privacy['authcode'], 'reg'=>1])->find();
            //     $userid = $userInfo['id'];
            //     $touserid = $touserInfo['id'];
            //     $privacyChat = true;
            // }
           

            // if ($userInfo['sex'] == '女' && $touserid != $kefu) {
            //     if (!$userInfo['yqr'] && $timenow - strtotime($userInfo['register_datetime']) < 7 * 86400 && $userInfo['realname_auth'] != 2) {
            //         $userConfig = M('config_personal')->where(['user_id' => $userid])->find();
            //         if (!$userConfig || $userConfig['chat_price'] == 0) {
            //             exit(json_encode(['code' => 400, 'msg' => '请先完成实名认证']));
            //         }
            //     }
            // }

            // $chatSingle = M('privatechat_user_single')->where(['user_id'=>$userid])->find();
            // $single = $chatSingle ? 2 : $single;


            $limittime = strtotime('2023-08-01 00:00:00');
            // if (time() >= $limittime) {
            //     if ((strtotime($userInfo['register_datetime']) < $limittime && strtotime($touserInfo['register_datetime']) > $limittime) || (strtotime($userInfo['register_datetime']) > $limittime && strtotime($touserInfo['register_datetime']) < $limittime)) {
            //         exit(json_encode(['code' => 400, 'msg' => '发送失败']));
            //     }
            // }

            if($kefu != $touserid && $kefu != $userid){
                if($type == 0 && ishasPhoneNumber($content)){
                    exit(json_encode(['code' => 400, 'msg' => '禁止发送手机号']));
                }
                if ($userInfo['sex'] == $touserInfo['sex']) {
                    if (strtotime($userInfo['register_datetime']) < $limittime || strtotime($touserInfo['register_datetime']) < $limittime || in_array($touserInfo['entertainment'], [0,2])) {
                        exit(json_encode(['code' => 400, 'msg' => '当前仅支持异性聊天']));
                    // } else {
                    //     $user_attestations = M('user_attestation','','DB_CONFIG9')->where(['user_id'=>['in', [$userid, $touserid]], 'status'=>1])->count();
                    //     if (!$user_attestations) {
                    //         exit(json_encode(['code' => 400, 'msg' => '双方均未经验认证']));
                    //     }
                    }
                }
                // if($content[0] == '[' && substr($content, -1) == ']'){

                // }else{
                //     $sendNum = M('privatechat')->where(['userid'=>$userid, 'content'=>$content])->count();
                //     if($sendNum >= 5){
                //         exit(json_encode(['code' => 400, 'msg' => '禁止重复刷屏']));
                //     }
                // }
            }

            if (!$userInfo || !$touserInfo || $userInfo['delete_time'] || $touserInfo['delete_time']) {
                exit(json_encode(['code' => 400, 'msg' => '账号已注销']));
            }

            //if (($userInfo['is_banned'] || $userInfo_privacy['is_banned']) && $kefu != $touserid) {
            // if ($userInfo['is_banned'] && strtotime($userInfo['banned_end_time']) > $timenow && $kefu != $touserid) {
            if ($userInfo['is_banned']){//被封号也不能私聊客服
                exit(json_encode(['code' => 400, 'msg' => '当前账号已被冻结']));
            }

            // if (!$userInfo['sandbox'] && $touserInfo['sandbox']) {
            //     exit(json_encode(['code' => 400, 'msg' => '无法给对方发送消息']));
            // }

            // $delChat = M('del_chat')->Query("select * from del_chat where (uid=$userid_privacy and to_uid=$touserid_privacy) or (uid=$touserid_privacy and to_uid=$userid_privacy)");
            // if ($delChat) {
            //     $del_ids = [$delChat[0]['id']];
            //     if (isset($delChat[1])) {
            //         $del_ids[] = $delChat[1]['id'];
            //     }
            //     M('del_chat')->where(['id' => ['in', $del_ids]])->delete();
            // }


            if ($kefu != $userid && $kefu != $touserid) {
                //if ($touserInfo['sex'] == '男' && $userInfo['sex'] == '女') {
                $touserConfig = ['chat_price' => 0];
                //} else {
                $touserConfig = M('config_personal')->where(['user_id' => $touserid])->find();

                if (!$touserConfig) {
                    $touserConfig = ['chat_price' => $config['chat_price']];
                } else {
                    $touserConfig = $config['chat_price_switch'] > 0 ? ['chat_price' => $config['chat_price']] : $touserConfig;
                }
                // $datetime = date('Y-m-d H:i:s');
                // $chat_discount = M('act_chat_discount_user')->where("user_id=$touserid and state=0 and starttime <= '$datetime' and endtime >= '$datetime'")->find();
                // if ($chat_discount) {
                //     $touserConfig['chat_price'] = number_format($touserConfig['chat_price'] * $chat_discount['discount'] / 100, 2);
                // }
                // $hasAttestation = M('user_attestation')->where(['user_id'=>$touserid, 'status'=>1])->count();
                //}
            }


            $free = 0;

            $status = 0;  // 好友关系或守护关系
            $money = 0;
            if (!in_array($kefu, [$userid, $touserid]) || !$greet) {
                if (!in_array($type, [9, 10])) {
                    if ($touserConfig['chat_price'] + 0) {
                        /*$attention1 = M('attention')->where(['user_id' => $userid, 'to_user' => $touserid])->find();
                        $attention2 = M('attention')->where(['user_id' => $touserid, 'to_user' => $userid])->find();

                        if (!$attention1 || !$attention2) {*/
                        /*$defend = M('user_defend')->where(['user_id' => $touserid, 'to_user' => $userid, 'angel' => 1])->find();
                        if (!$defend) {*/
                        $status = 1;
                        //}
                        //}
                    }
                }
            }

            $chat_free = 0;
            if ($userid < $touserid) {
                $couple_a = $userid . ',' . $touserid;
            } else {
                $couple_a = $touserid . ',' . $userid;
            }

            /**
             * 双向收费
             */
            // 是否已设置付费方
            $ChargeStatus = 0;
            if ($kefu != $userid && $kefu != $touserid) {
                if(isset($config['two_way_charge_status']) && $config['two_way_charge_status']){
                    $two_way_charge_reg_time = isset($config['two_way_charge_reg_time']) ? strtotime($config['two_way_charge_reg_time']) : 0;
                    $male = $userInfo['sex'] == '女' ? $touserInfo : $userInfo;
                    // 应只对男用户限制双向收费。若注册时间早于开启时间，则默认男用户付费
                    if(strtotime($male['register_datetime']) > $two_way_charge_reg_time){
                        $ChatChargeRecordsMap = $touserid < $userid ? [
                            'user_id' => $touserid,
                            'another_id' => $userid,
                        ] :  [
                            'user_id' => $userid,
                            'another_id' => $touserid,
                        ];
                        $ChatChargeRecords = M('chat_charge_records')->master(true)->where($ChatChargeRecordsMap)->find();
                        if ($ChatChargeRecords) {
                            if($ChatChargeRecords['state']){
                                $ChargeStatus = 1;
                                if ($ChatChargeRecords['payer'] == $userid) {
                                    $recharge_user = $userInfo;
                                } else {
                                    $recharge_user = $touserInfo;
                                    $chat_free = 1;
                                }
                            } else {
                                // 若未设置付费者
                                if ($ChatChargeRecords['payer'] == 0 || $ChatChargeRecords['state'] == 0) {
                                    if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男') {
                                        if ($touserInfo['entertainment'] == 1) {
                                            $ChatChargeRecordsMap['payer'] = $userid;
                                            $ChatChargeRecordsMap['state'] = 1;
                                            $recharge_user = $userInfo;
                                        } else if ($ispayer == 1) {
                                            $ChatChargeRecordsMap['payer'] = $userid;
                                            $ChatChargeRecordsMap['state'] = 1;
                                            $recharge_user = $userInfo;
                                        } else {
                                            $ChatChargeRecordsMap['payer'] = $touserid;
                                            $ChatChargeRecordsMap['state'] = 0;
                                            $recharge_user = $touserInfo;
                                            $chat_free = 1;
                                        }
                                    } else {
                                        $ChatChargeRecordsMap['payer'] = $userid;
                                        $ChatChargeRecordsMap['state'] = 1;
                                        $recharge_user = $userInfo;
                                    }
                                    $ChatChargeRecordsMap['id'] = $ChatChargeRecords['id'];

                                    M('chat_charge_records')->save($ChatChargeRecordsMap);
                                    $ChargeStatus = 1;
                                } elseif ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男') {
                                    // exit(json_encode(['code' => 400, 'msg' => '等待付费方确认']));
                                } else {
                                    // 兼容旧版 回复消息则代表确认
                                    M('chat_charge_records')->where(['id'=>$ChatChargeRecords['id']])->save(['state' => 1]);
                                    $recharge_user = $userInfo;
                                    $ChargeStatus = 1;
                                }
                                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid, json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $touserid_privacy]));
                                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $userid_privacy]));
                            }
                        } else {
                            $ChatChargeRecordsMap['time'] = $timenow;
                            if ($touserInfo['entertainment'] == 1) {
                                $ChatChargeRecordsMap['payer'] = $userid;
                                $ChatChargeRecordsMap['state'] = 1;
                                $recharge_user = $userInfo;
                            // } else if ($userInfo['yqr'] && $userInfo['yqr'] == $touserInfo['yqm']) {
                            //     $ChatChargeRecordsMap['payer'] = $userid;
                            //     $ChatChargeRecordsMap['state'] = 1;
                            //     $recharge_user = $userInfo;
                            // } else if ($userInfo['yqm'] && $userInfo['yqm'] == $touserInfo['yqr']) {
                            //     $ChatChargeRecordsMap['payer'] = $touserid;
                            //     $ChatChargeRecordsMap['state'] = 1;
                            //     $recharge_user = $touserInfo;
                            } else if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男') {
                                if ($ispayer == 1) {
                                    $ChatChargeRecordsMap['payer'] = $userid;
                                    $ChatChargeRecordsMap['state'] = 1;
                                    $recharge_user = $userInfo;
                                } else {
                                    $ChatChargeRecordsMap['payer'] = $touserid;
                                    $ChatChargeRecordsMap['state'] = 0;
                                    $recharge_user = $touserInfo;
                                    $chat_free = 1;
                                }
                            } else {
                                $ChatChargeRecordsMap['payer'] = $userid;
                                $ChatChargeRecordsMap['state'] = 1;
                                $recharge_user = $userInfo;
                            }

                            M('chat_charge_records')->add($ChatChargeRecordsMap);
                            $ChargeStatus = 1;
                        }
                    }
                }
            }

            if (!$notice && $userInfo['sex'] == '女' && $userInfo['id'] != $kefu && $touserInfo['id'] != $kefu && !in_array($userInfo['realname_auth'], [1,2]) && $userInfo['entertainment'] != 1) {
                $userData = M('user_data')->where(['user_id'=>$touserInfo['id']])->find();
                if($userData && $userData['topup'] > 0) {
                    exit(json_encode(['code' => 400, 'msg' => '请先实名']));
                }
            }

            //  其中一方属于系统推送过来的，只有男方是需要付费。否则，谁先发起对话，双方费用需都承担
            if (($userInfo['sex'] == '女' && $touserInfo['sex'] == '男' || $touserInfo['entertainment'] == 1) && $touserInfo['id'] != $kefu) {
                // if($userInfo['realname_auth'] != 2 && strtotime('2023-06-01') > strtotime($userInfo['register_datetime'])){
                //     exit(json_encode(['code' => 400, 'msg' => '未实名认证']));
                // }
                if($userInfo['yqm'] != $touserInfo['yqr'] && ($fate==0 && $timing==0 && $greet==0)){

                    // $selfpush = M('chat_lists')->where(['user_id'=>$userid_privacy, 'another_id'=>$touserid_privacy])->find();
                    // // $selfpull = M('chat_lists')->where(['another_id'=>$userid_privacy, 'user_id'=>$touserid_privacy])->find();
                    //  $selfpull = M('chat_lists')->where(['user_id'=>$touserid_privacy, 'another_id'=>$userid_privacy])->find();
                    $otherlimit = !in_array($type, [20,22]);
                    if ($touserInfo['entertainment'] == 1) {
                        if ($ChargeStatus) {
                            // if ($recharge_user['id'] != $userInfo['id'] || ($recharge_user['id'] == $userInfo['id'] && $touserConfig['chat_price'] == 0)) {
                            //     if(($selfpush && $selfpush['user_first'] == 1) || ($selfpull && $selfpull['another_first'] == 1)){
                            //         // exit(json_encode(['code' => 400, 'msg' => '等待对方回复后才可继续聊天']));
                            //     }
                            // }
                        } else {
                            $recharge_user = $userInfo;
                            $ChargeStatus = 1;
                        }
                    } else {
                        // if($userInfo['realname_auth'] != 2 && $userInfo['yqm'] != $touserInfo['yqr'] && $kefu != $touserid && $kefu != $userid){
                            // $isHasChatWin = M()->Query("(select id from chat_lists where user_id=$touserid and another_id=$userid) union (select id from chat_lists where user_id=$userid and another_id=$touserid)");
                            // if(!$selfpush && !$selfpull && $otherlimit && $kefu != $userid){
                            //     // exit(json_encode(['code' => 400, 'msg' => '未实名认证不能主动向男用户发信息']));
                            //     exit(json_encode(['code' => 401, 'msg' => '不能主动向男用户发信息']));
                            // }
                        // }

                        if($kefu != $touserid && $kefu != $userid && $otherlimit){
                            // if(($selfpush && $selfpush['user_first'] == 1) || ($selfpull && $selfpull['another_first'] == 1)){
                            //     // if ($type == 1) {
                            //     //     if($userInfo['realname_auth'] != 2 && $userInfo['yqm'] != $touserInfo['yqr']){
                            //     //         exit(json_encode(['code' => 400, 'msg' => '未实名认证']));
                            //     //     }
                            //     //     $fate = 1;
                            //     // } else {
                            //         // exit(json_encode(['code' => 400, 'msg' => '等待对方回复后才可继续聊天']));
                            //     // }
                            // }
                            // 亲密度
                            if($type == 0){
                                $intimate = M('user_intimate')->where(['couple_a' => $couple_a])->getField('intimate');
                                if(!$intimate || $intimate <= 0){
                                    if(is_hasNumber($content)){
                                        $cachekeyPSE = 'RSE'.$userid_privacy.'to'.$touserid_privacy;
                                        if (!S($cachekeyPSE)) {
                                            S($cachekeyPSE, 1, 10);
                                            M('privatechat_send_error')->add(['user_id'=>$userid_privacy, 'another_id'=>$touserid_privacy, 'content'=>$content, 'time'=>$timenow, 'reason_type'=>1]);
                                        }
                                        exit(json_encode(['code' => 400, 'msg' => '对方回复后即可发数字']));
                                    }
                                }
                            }
                        }
                    }
                }

                //$greetRecords = M()->Query("select id from greet_records where (user_id=$touserid and to_user=$userid) or (user_id=$userid and to_user=$touserid)");
                // $greetRecords = false;

                // if ($greetRecords) {
                //     $status = 0;
                //     $recharge_user = $touserInfo;
                // } else {
                //     $recharge_user = $userInfo;
                // }
                if (!$ChargeStatus) {
                    $recharge_user = $touserInfo;
                    $chat_free = 1;
                }
            } else {
                if (!$ChargeStatus) {
                    $recharge_user = $userInfo;
                }
            }

            // 我付费，对方免费的情况下，首次发起聊天算打招呼，打招呼有上限
            if ($recharge_user['id'] == $userInfo['id'] && $touserConfig['chat_price'] <= 0 && $userInfo['id'] != $kefu && $touserInfo['id'] != $kefu) {

                $minuid = min($userInfo['id'], $touserInfo['id']);
                $maxuid = max($userInfo['id'], $touserInfo['id']);
                $ischatList = M('chat_lists')->where(['user_id'=>$minuid, 'another_id'=>$maxuid])->find();
                $touserUnReply = ($userInfo['id'] == $minuid && $ischatList['user_first']) || ($userInfo['id'] == $maxuid && $ischatList['another_first']);

                if ($touserUnReply) {
                    // exit(json_encode(['code' => 400, 'msg' => '等待对方回复后才可继续聊天']));
                }
                if (!$ischatList) {
                    $fate = 1;
                    $timing = 1;

                    $sayhiNum = 10;
                    if ($userInfo['noble_grade'] && $userInfo['noble_time'] > time()) {
                        $privilege = M('grade_noble')->where(['grade' => $userInfo['noble_grade']])->getField('privilege');
                        $privilege = explode(',', $privilege);
                        if (in_array(17, $privilege)) {
                            $sayhiNum = 50;
                        }
                    }

                    // $fateuids = M('privatechat')->where(['userid'=>$userInfo['id'], 'is_fate'=>1, 'is_public'=>1, 'money'=>0, 'addtime'=>['egt', date('Y-m-d') . ' 00:00:00']])->getField('touserid', true);
                    // $fateuids = $fateuids ? $fateuids : [];
                    // if (sizeof($fateuids) >= $sayhiNum) {
                    //     exit(json_encode(['code'=>400, 'msg'=>'今日打招呼次数已达上限']));
                    // }
                    $is_public = 1;
                }

            }

            // 服务订单下生成的免费聊天权限
            // $privatechat_free = M('privatechat_free')->where(($userid>$touserid?"user_id=$touserid and another_id=$userid":"user_id=$userid and another_id=$touserid") . " and ((end_time=0 or start_time=0 or end_time>$timenow) or ((server=$userid and confirm in (1,2)) or (server=$touserid and confirm in (1,3))))")->order('id asc')->find();
            // if ($userid == $userid_privacy) {
            //     $privatechat_free = M('privatechat_free')->where(($userid>$touserid?"user_id=$touserid and another_id=$userid":"user_id=$userid and another_id=$touserid") . " and (end_time=0 or start_time=0 or end_time>$timenow)")->order('id asc')->find();
            //     if ($privatechat_free) {
            //         if ($privatechat_free['start_time'] == 0) {
            //         // 说明是线上订单，服务方未发起聊天
            //             if ($privatechat_free['server'] == $userid) {
            //                 // M('privatechat_free')->where(['id'=>$privatechat_free['id']])->save(['start_time'=>$timenow, 'end_time'=>$timenow + $privatechat_free['end_time'] - $privatechat_free['create_time']]);
            //                 M('privatechat_free')->where(['id'=>$privatechat_free['id']])->save(['start_time'=>$timenow, 'end_time'=>9999999999]);
            //                 Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['another_id']]));
            //                 Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['another_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['user_id']]));
            //                 $chat_free = 1;
            //             }
            //         // } else if ($privatechat_free['confirm'] != 0) {
            //         //     if ($privatechat_free['confirm'] == 1) {
            //         //         Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['another_id']]));
            //         //         Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['another_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['user_id']]));
            //         //     } else if ($privatechat_free['server'] == $userid) {
            //         //         Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['another_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['user_id']]));
            //         //     } else {
            //         //         Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['another_id']]));
            //         //     }
            //         } else {
            //             $lianmaiMinute = $privatechat_free['audio_second'] + $privatechat_free['video_second'] > 0 ? ceil(($privatechat_free['audio_second'] + $privatechat_free['video_second']) / 60) : 0;
            //             $free_over = false;
            //             if ($lianmaiMinute == 0) {
            //                 if ($privatechat_free['seller_msg'] >= 200) {
            //                     $free_over = true;
            //                 }
            //             } elseif ($lianmaiMinute <= 10) {
            //                 if ($privatechat_free['seller_msg'] >= 150) {
            //                     $free_over = true;
            //                 }
            //             } elseif ($lianmaiMinute <= 20) {
            //                 if ($privatechat_free['seller_msg'] >= 100) {
            //                     $free_over = true;
            //                 }
            //             } elseif ($lianmaiMinute <= 30) {
            //                 if ($privatechat_free['seller_msg'] >= 50) {
            //                     $free_over = true;
            //                 }
            //             } elseif ($lianmaiMinute < 35) {
            //                 if ($privatechat_free['seller_msg'] >= 0) {
            //                     $free_over = true;
            //                 }
            //             } elseif ($lianmaiMinute >= 35) {
            //                 $free_over = true;
            //             }
            //             if ($free_over) {
            //                 M('privatechat_free')->where(['id'=>$privatechat_free['id']])->save(['end_time'=>time()]);
            //                 Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['another_id']]));
            //                 Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['another_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['user_id']]));
            //             } else {
            //                 $chat_free = 1;
            //             }
            //         }
            //     }
            // }
            if ($userid < $touserid) {
                $field_count = 'count_a';
                $couple_a = $userid_privacy . ',' . $touserid_privacy;
                $couple_b = $touserid_privacy . ',' . $userid_privacy;
            } else {
                $field_count = 'count_b';
                $couple_a = $touserid_privacy . ',' . $userid_privacy;
                $couple_b = $userid_privacy . ',' . $touserid_privacy;
            }

            $overpayscale = 0;
            // $topcust = 100000;
            // $maxscale = 10;
            $intimate = M('user_intimate')->master(true)->where(['couple_a' => $couple_a])->find();
            // if ($intimate && $intimate['intimate'] >= $topcust) {
            //     $overpayscale = $maxscale;
            // } else {
                // 获取所有关联账号的总支付
                $uids = [];
                $phone = $userInfo['phone'];
                $uids = M('recycle_user')->where(['phone'=>$phone])->getField('user_id', true);
                if ($uids) {
                    $uids[] = $userid;
                    $uids = array_unique($uids);
                    if (sizeof($uids) <= 1) {
                        $uids = [];
                    }
                }
                $device_ids = M('user_repeat_check')->where(['user_id'=>$userid])->getField('device_ids');
                if (($device_ids || $uids) && false) {
                    $device_users = [];
                    $device_userids = [$userid];
                    if ($device_ids) {
                        $device_ids = explode(',', $device_ids);
                        foreach ($device_ids as $device_id) {
                            $devusers = M('user_repeat_check')->where(['_string'=>'FIND_IN_SET('."'$device_id'".',device_ids)'])->cache(true,600)->getField('user_id',true);
                            if ($devusers) {
                                foreach ($devusers as $devuser) {
                                    $device_userids[] = $devuser;
                                    if ($devuser == $touserid) {
                                        continue;
                                    }
                                    if ($devuser > $touserid) {
                                        if (!in_array($touserid . ',' . $devuser, $device_users)) {
                                            $device_users[] = $touserid . ',' . $devuser;
                                        }
                                    } else {
                                        if (!in_array($devuser . ',' . $touserid, $device_users)) {
                                            $device_users[] = $devuser . ',' . $touserid;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    foreach ($uids as $value) {
                        $device_userids[] = $value;
                        if ($value == $touserid) {
                            continue;
                        }
                        if ($value > $touserid) {
                            if (!in_array($touserid . ',' . $value, $device_users)) {
                                $device_users[] = $touserid . ',' . $value;
                            }
                        } else {
                            if (!in_array($value . ',' . $touserid, $device_users)) {
                                $device_users[] = $value . ',' . $touserid;
                            }
                        }
                    }
                    $device_users = array_unique($device_users);
                    $device_userids = array_unique($device_userids);
                    // var_dump($device_userids);exit;
                    // $topupCount = M('user_data')->where(['user_id' => ['in', $device_userids]])->sum('topup');
                    $topupCount = 0;
                    // var_dump($topupCount);exit;
                    if ($topupCount >= 500) {
                        $overpayscale = 60;
                        if ($topupCount >= 15000) {
                            $overpayscale = 30;
                        } elseif ($topupCount >= 10000) {
                            $overpayscale = 50;
                        }
                    } else if (sizeof($device_users)) {
                        $allpays = M('user_intimate')->where(['couple_a' => ['in', $device_users]])->sum('intimate');

                        // exit(json_encode(['code' => 400, 'msg' => $allpays]));
                        // if ($allpays >= $topcust) {
                        //     $overpayscale = $maxscale;
                        // }
                        if ($allpays >= 5000 * 5) {
                            $overpayscale = 30;
                        } else if ($allpays >= 3000 * 5) {
                            $overpayscale = 50;
                        } else if ($allpays >= 1500 * 5) {
                            $overpayscale = 70;
                        }
                    }
                } else {
                    // $topupCount = M('user_data')->where(['user_id' => $userid])->sum('topup');
                    // if ($topupCount >= 500) {
                    //     $overpayscale = 60;
                    //     if ($topupCount >= 15000) {
                    //         $overpayscale = 30;
                    //     } elseif ($topupCount >= 10000) {
                    //         $overpayscale = 50;
                    //     }
                    // }
                }
            // }
            if ($overpayscale) {
                $chat_scale['scale'] = $overpayscale;
            } else {
                // $chat_scale = M('limit_chat_price')->where($userInfo['id']>$touserInfo['id'] ? 'user_id='.$touserInfo['id']. ' and another_id='. $userInfo['id'] : 'user_id='.$userInfo['id']. ' and another_id='. $touserInfo['id'])->find();
                $chat_scale ='';
            }
            // $serviceOrder = M('order_of_service')->where("((user_id=$userid and shopowner=$touserid) or (user_id=$touserid and shopowner=$userid)) and status in (0, 1) and state = 0 and paystate=1 and type=1")->count();
            // if ($serviceOrder) {
            //     $chat_free = 1;
            // }
            // $hasnotdec = in_array($recharge_user['id'], explode(',', $config['chat_over_dec_not']));


            // if ($userInfo['entertainment'] == 1 && $touserInfo['entertainment'] != 1) {
            //     $minuid = min($userInfo['id'], $touserInfo['id']);
            //     $maxuid = max($userInfo['id'], $touserInfo['id']);
            //     $ischatList = M('chat_lists')->where(['user_id'=>$minuid, 'another_id'=>$maxuid])->find();
            //     if (!$ischatList) {
            //         M('user')->where(['id'=>$userInfo['id']])->setField('entertainment', $touserInfo['entertainment']);
            //     }
            // }

            switch ($type) {
                case 0:
                    if ($content == '') exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    if ($userid != $kefu) {
                        // 敏感词检测
                        $contain = M('filter_word')->cache(true, 3600)->where(['state' => 1])->getField('name', true);
                        foreach ($contain as $k => $v) {
                            if (stripos($content, $v) !== false) {
                                exit(json_encode(['code' => 400, 'msg' => '消息含有敏感词"' . $v . '",请重新编辑发送']));
                            }
                        }
                        // $contain = M('ban_word')->cache(true, 3600)->where(['state' => 1])->getField('name', true);
                        $contain = M('ban_word')->where(['state' => 1])->getField('name', true);
                        $maskArr = ['','*','**','***','****','*****'];
                        $sysMask = false;
                        foreach ($contain as $k => $v) {
                            if (stripos($content, $v) !== false) {
                                $content = str_replace($v, $maskArr[mb_strlen($v)]??'*', $content);
                                $sysMask = true;
                            }
                        }
                    }

                    if (!$timing) {

                        $extraMoney = 0;

                        if ($kefu != $userid && $kefu != $touserid) { // 非客服咨询
                            /*if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $touserInfo['is_identity_authentication'] == 2) {
                                $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $userid, 'touserid' => $touserid])->find();
                                if (!$chatRecord) {
                                    $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $touserid, 'touserid' => $userid])->order('id desc')->find();
                                    if ($chatRecord) {
                                        $extraMoney = 1;
                                    }
                                }
                            }*/
                            $check_hour = 1;
                            $check_num = 10;
                            $check_banned = 12;
                            $ten_minutes = 0;
                            // $ten_minutes = M('privatechat')->where([
                            //     'userid'=>$userid_privacy,
                            //     'content'=>$content,
                            //     'addtime'=>['egt', date('Y-m-d H:i:s', strtotime('-'.$check_hour.' minutes'))]
                            // ])->count();
                            if ($ten_minutes >= $check_num - 1) {
                                M('warn_user_chat_records')->add([
                                    'user_id'=>$userid_privacy,
                                    'content'=>$content,
                                    'reason'=>$check_hour.'分钟内发有'.$check_num.'条相同内容',
                                    'time'=>time()
                                ]);
                                if ($userInfo['is_banned'] != 1) {
                                    M('user')->where(['id'=>$userid])->save(['is_banned'=>1,'banned_end_time'=>date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours')), 'banned_desc'=>$check_hour.'分钟内发有'.$check_num.'条相同内容']);
                                    M('config_personal')->where(['user_id'=>$userid])->save(['is_read_rule'=>0]);
                                    $userInfo['is_banned'] = 1;
                                    M('admin_logs')->add([
                                        'channel' => 3,
                                        'toward' => 0,
                                        'money' => 0,
                                        'user_id' => $userid,
                                        'content' => $check_hour.'分钟内发有'.$check_num.'条相同内容,封禁账号至' . date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours'))
                                    ]);
                                }
                            } else {
                                // $ten_minutes = M('privatechat')->master(true)->where([
                                //     'userid'=>$userid_privacy,
                                //     'content'=>$content,
                                //     'addtime'=>['egt', date('Y-m-d H:i:s', strtotime('-1 minutes'))],
                                //     'is_fate'=>0
                                // ])->count();
                                if ($ten_minutes > 18) {
                                    $hasrecords = M('warn_user_chat_records')->master(true)->where([
                                        'user_id'=>$userid_privacy,
                                        'content'=>mb_substr($content, 0, 50),
                                        'time'=>['egt', strtotime(date('Y-m-d'))]
                                    ])->find();
                                    if ($hasrecords) {
                                        M('warn_user_chat_records')->where([
                                            'id'=>$hasrecords['id']
                                        ])->save(['time'=>time()]);
                                    } else {
                                        M('warn_user_chat_records')->add([
                                            'user_id'=>$userid_privacy,
                                            'content'=>$content,
                                            'reason'=>'1分钟内发有20条相同内容',
                                            'time'=>time()
                                        ]);
                                    }
                                }
                            }

                            // if ($userInfo['sex'] == '女') {
                                // $arr = preg_split("/([a-zA-Z0-9]+)/", $content, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
                                // foreach ($arr as $key => $value) {
                                //     if (!preg_match("/([a-zA-Z0-9]+)/", $value)) continue;
                                //     if ($userInfo['is_banned'] == 1) break;
                                //     if (!empty(trim($value)) && mb_strlen($value, 'UTF-8') == strlen($value) && strlen($value) > 1) {
                                //         $check_hour = 1;
                                //         $check_num = 20;
                                //         $check_banned = 12;
                                //         $hours1 = M('privatechat')->master(true)->where([
                                //             'userid'=>$userid_privacy,
                                //             'type'=>0,
                                //             'content'=>['like','%'.$value.'%'],
                                //             'addtime'=>['egt', date('Y-m-d H:i:s', strtotime('-'.$check_hour.' hours'))]
                                //         ])->limit($check_num)->count();

                                //         if ($hours1 >= $check_num - 1) {
                                //             M('warn_user_chat_records')->add([
                                //                 'user_id'=>$userid_privacy,
                                //                 'reason'=>$check_hour.'小时内连发'.$check_num.'次带有相同数字组 封号'.$check_banned.'小时',
                                //                 'content'=>$value,
                                //                 'time'=>time()
                                //             ]);
                                //             if ($userInfo['is_banned'] != 1) {
                                //                 M('user')->where(['id'=>$userid])->save(['is_banned'=>1,'banned_end_time'=>date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours')), 'banned_desc'=>'系统检测到违规批量发联系方式给平台用户，涉嫌欺骗']);
                                //                 M('config_personal')->where(['user_id'=>$userid])->save(['is_read_rule'=>0]);
                                //                 $userInfo['is_banned'] = 1;

                                //                 M('admin_logs')->add([
                                //                     'channel' => 3,
                                //                     'toward' => 0,
                                //                     'money' => 0,
                                //                     'user_id' => $userid,
                                //                     'content' => '短时间内发送多条相同字母&数字组,封禁账号至' . date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours'))
                                //                 ]);


                                //                 $auto_content = "系统检测到违规批量发联系方式给平台用户，涉嫌欺骗，封禁账号至".date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours'));
                                //                 // $contain_tip = ['single' => 1, 'userid' => $kefu, 'touserid' => $userid, 'content' => $auto_content, 'finish' => 0, 'type'=>-3, 'data'=>json_encode(['type'=>1, 'content'=>'申请解除封号','state'=>0], JSON_UNESCAPED_UNICODE)];
                                //             }
                                //         }
                                //     }
                                // }
                            // }

                        } else {
                            $chat_free = 1;
                        }
                        $is_push = 1;
                        if (!$chat_free) {
                            if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                                $money = $touserConfig['chat_price'];

                                if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                    $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->cache(true, 360)->find();
                                    if ($gradeNoble) {
                                        $privilege = explode(',', $gradeNoble['privilege']);

                                        if (in_array(10, $privilege)) {
                                            $privilegeValue = explode(',', $gradeNoble['value']);

                                            if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                                $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                                $privilegeValue[0] = intval($privilegeValue[0]);

                                                if ($privilegeValue[0] > $userCount) {
                                                    M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                    //$touserConfig['chat_price'] = 0;

                                                    $free = 1;
                                                }
                                            }
                                        }
                                    }
                                }


                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }

                                if (!$free) {
                                    if ($recharge_user['free_chat']) {
                                        /*$chatCount = M('chat_records')->where(['types' => $type, 'user_id' => $userid])->count();

                                        if ($chatCount >= $config['chat_count']) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            M('chat_records')->add(['types' => $type, 'user_id' => $userid, 'to_user' => $touserid, 'create_time' => time()]);

                                            $money = 0;
                                        }*/

                                        M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                        $free = 1;
                                    } else {
                                        // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100) ? 0.1 : 0;
                                        // $extra_recharge_rate = $recharge_user['volley'] > 100 && !$hasnotdec ? 0.1 : 0;
                                        $extra_recharge_rate = 0;
                                        if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                            if ($recharge_user['id'] == $userid) {
                                                exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                            } else {
                                                exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                            }
                                        }
                                    }
                                }
                            }

                            $money = $free ? 0 : $money;
                            if ($chat_scale && $money) {
                                $money = $money * $chat_scale['scale'] / 100;
                                $money = $money < 0.1 ? 0.1 : $money;
                            }
                            if ($recharge_user['id'] == $userid) {
                                // if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                if ($free && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                                } else {
                                    $chat_score = $money;
                                }

                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, 'single' => $single, 'score' => $chat_score * 1];
                                $contain['send_sex'] = $userInfo['sex'];
                            } else {
                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, 'single' => $single, 'score' => 0];
                            }

                            /*if ($recharge_user['id'] == $userid) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }*/

                            /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => ($chat_score + $extraMoney) * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }*/
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'finish' => 1, 'single' => $single];
                            if ($touserid_privacy == $kefu && $single) {
                                $is_push = 0;
                            }
                        }


                        // 添加聊天
                        // $id = M('privatechat')->add($contain);
                        // $contain['id'] = $id;
                        $pushNewMsgs[] = $contain;
                        
                        if ($is_push) {
                        // 更新会话列表
                        D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, $content, 0, $userInfo['sex']);
                        }

                        if (isset($contain_tip) && !empty($contain_tip)) {
                            $pushNewMsgs[] = $contain_tip;
                            // 更新会话列表
                            D('ChatLists')->updateLists($contain_tip['userid'], $contain_tip['touserid'], 1, $contain_tip['type'], $contain_tip['content']);
                        }

                        // 男性 客服自动回复
                        // if ($userInfo['sex'] == '男' && $kefu == $touserid) {
                        //     $auto_customer_service = 0;

                        //     $customer_service_chat = M('customer_service_chat')->where(['user_id' => $userid])->find();
                        //     if ($customer_service_chat) {
                        //         if (($customer_service_chat['create_time'] + 3600) < time()) {
                        //             $auto_customer_service = 1;
                        //             M('customer_service_chat')->where(['id' => $customer_service_chat['id']])->setField('create_time', time());
                        //         }
                        //     } else {
                        //         $auto_customer_service = 1;
                        //         M('customer_service_chat')->add(['user_id' => $userid, 'create_time' => time()]);
                        //     }

                            // if ($auto_customer_service) {
                            //     $auto_content = "由于用户群体比较大，人工客服只能处理身份审核以及突发事件，如需举报，投诉可去用户资料页去投诉用户，如需联系平台，可以去留言。感谢你的支持";
                            //     $contain = ['single' => 1, 'userid' => $touserid, 'touserid' => $userid, 'content' => $auto_content, 'finish' => 1];
                            //     // $id = M('privatechat')->add($contain);

                            //     // $contain['id'] = $id;
                            //     $pushNewMsgs[] = $contain;

                            //     // 更新会话列表
                            //     D('ChatLists')->updateLists($touserid, $userid, 1, 0, $auto_content);
                            // }
                        // }


                        // 提醒词记录
                        if ($kefu != $userid && $kefu != $touserid) {
                            $warnWord = M('chat_tip_word')->where(['is_hidden' => 0, 'sex'=>['in', ['均可', $userInfo['sex']]]])->cache(true, 5)->getField('id, title, single, content');
                            foreach ($warnWord as $k => $v) {
                                if ($v['title']=='*' && $sysMask) continue;
                                if (stripos($content, $v['title']) !== false) {
                                    $contain = ['type' => -1, 'single' => $v['single'], 'userid' => $userid_privacy, 'touserid' => $touserid_privacy, 'content' => $v['content'], 'finish' => 1];
                                    // $id = M('privatechat')->add($contain);

                                    // $contain['id'] = $id;
                                    $pushNewMsgs[] = $contain;

                                    $isWarnWord = 1;

                                    //$this->getNewMsg(json_encode(['userid' => $userid, 'touserid' => $touserid, 'type' => -1]));
                                    break;
                                }
                            }
                        }

                        if ($extraMoney) {
                            $rewardContent = '🎉🎉 恭喜，你的魅力吸引了小哥哥<br>👄 24小时内回复消息还可额外获得金币<br><br>上传更多照片能获得更多搭讪和积分哦~';
                            $contain_1 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => -1, 'single' => 1, "content" => $rewardContent, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                            // $id = M('privatechat')->add($contain_1);

                            // $contain_1['id'] = $id;
                            $pushNewMsgs[] = $contain_1;
                        }
                    } else {
                        $location = I('location');  // 带有跳转链接

                        if ($location) {
                            $datas = I('data');
                            $datas = htmlspecialchars_decode($datas);
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'location' => $location, 'data' => $datas, 'finish' => 1];
                            // $id = M('privatechat')->add($contain);

                            // $contain['id'] = $id;
                            $pushNewMsgs[] = $contain;

                            // 更新会话列表
                            D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, 0, $content);
                        } else {
                            $speed = intval(I('speed'));  // 速配
                            $match = intval(I('match'));  // 夫妻相
                            //$fate = intval(I('fate'));  // 今日缘分

                            if ($speed) {
                                $types = $userInfo['sex'] == '男' ? 2 : 1;

                                $content_default = M('privatechat_default')->where(['types' => $types, 'channel' => 2, 'user_id' => ['in', [0, $touserid]]])->order('rand()')->getField('content');

                                if (!$content_default) {
                                    $content_default = M('privatechat_zhaohu')->where(['types' => $types, 'is_hidden' => 0])->order('rand()')->getField('content');
                                }
                                $speedContent = '❤ 同城速配成功，快把握住缘分吧~';
                                $contain_1 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => 0, 'single' => 1, "content" => $content];
                                $contain_2 = ["userid" => $touserid_privacy, "touserid" => $userid_privacy, "type" => 0, 'single' => 1, "content" => $content_default];
                                $contain_3 = ["userid" => $touserid_privacy, "touserid" => $userid_privacy, "type" => -1, 'single' => 1, "content" => $speedContent, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];

                                // $id = M('privatechat')->add($contain_1);
                                // $contain_1['id'] = $id;
                                $pushNewMsgs[] = $contain_1;
                                // $id = M('privatechat')->add($contain_2);
                                // $contain_2['id'] = $id;
                                $pushNewMsgs[] = $contain_2;
                                //M('privatechat')->add($contain_3);

                                // 更新会话列表
                                D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 1, 0, $content);
                                D('ChatLists')->updateLists($touserid_privacy, $userid_privacy, 1, 0, $content_default);

                            } else if ($match) {
                                $matchContent = '👫 经大数据测算，你和对方具有夫妻相<br>👄 赶快向Ta打个招呼，把握缘分哦~';
                                $contain_1 = ["userid" => $touserid_privacy, "touserid" => $userid_privacy, "type" => -1, 'single' => 1, "content" => $matchContent, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                                $contain_2 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => 0, "content" => $content, 'finish' => 1];

                                //M('privatechat')->add($contain_1);
                                // $id = M('privatechat')->add($contain_2);
                                // $contain_2['id'] = $id;
                                $pushNewMsgs[] = $contain_2;

                                // 更新会话列表
                                D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, 0, $content);
                            } else if ($fate) {
                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "content" => $content, 'finish' => 1, 'is_fate' => 1, "single" => $single, "is_public" => $is_public];

                                $singleFate = 0;
                                if ($userInfo['sex'] == '女' && $userInfo['quality'] == 1) {
                                    // $contain['id'] = M('privatechat')->order('id desc')->getField('id');
                                    $contain['single'] = 2;
                                    $singleFate = 2;
                                }

                                // $id = M('privatechat')->add($contain);
                                // $contain['id'] = $id;
                                $pushNewMsgs[] = $contain;
                                // 更新会话列表
                                D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $singleFate, 0, $content, $single == 2?2:1);
                            } else if ($login_greet) {
                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, 'single' => 1, "content" => $content, 'finish' => 1];

                                // $id = M('privatechat')->add($contain);
                                // $contain['id'] = $id;
                                $pushNewMsgs[] = $contain;
                            } else if ($notice) {
                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, 'single' => $single, "content" => $content, 'finish' => 1];

                                // $id = M('privatechat')->add($contain);
                                // $contain['id'] = $id;
                                $pushNewMsgs[] = $contain;
                                // 更新会话列表
                                D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, $content, $quality ? 2 : 0);
                            } else {
                                if ($userInfo['sex'] == '男') {
                                    $content = '❤ ← 丘比特 → 发现你俩今天很有缘，为你们牵线成功~';
                                    $greetContent = '❤ ← 丘比特 → 牵线成功，给对方发消息可领取红包奖励';
                                    $contain_1 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => 0, 'single' => 1, "content" => $content, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE)];
                                    $contain_2 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => -1, 'single' => 1, "content" => $greetContent, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE), 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                                } else {
                                    $greetContent = '❤ ← 丘比特 → 发现你俩今天很有缘~ <br>👄 赶紧聊聊吧，别错过缘分~';
                                    $contain_1 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => -1, 'single' => 1, "content" => $greetContent, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE), 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                                    $contain_2 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => 0, 'single' => 1, "content" => $content, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE), 'finish' => 1];
                                }

                                // $id = M('privatechat')->add($contain_1);
                                // $contain_1['id'] = $id;
                                $pushNewMsgs[] = $contain_1;
                                // $id = M('privatechat')->add($contain_2);
                                // $contain_2['id'] = $id;
                                $pushNewMsgs[] = $contain_2;
                            }
                        }
                    }

                    // if ($userid != $kefu && !$greet && !$notice) {
                        // 日常任务
                        /*$task = M('task')->where(['name' => 'word_chat'])->find();
                        if (($task['reward'] + 0) && ($task['max'] + 0)) {
                            $start = strtotime(date('Ymd'));
                            //$cost = M('volley_desc')->where(['user_id' => $userid, 'content' => '[完成任务] ' . $task['title'], 'time' => ['egt', $start]])->sum('price');

                            $cost = M('task_daily')->where(['user_id' => $userid, 'name' => $task['name'], 'create_time' => ['egt', $start]])->sum('reward');

                            if (($cost + $task['reward']) <= $task['max']) {
                                D('Task')->updateTaskDaily($userid, $task['name'], $task['reward']);

                                M('user_task')->add(['task' => $task['name'], 'user_id' => $userid, 'create_time' => time()]);

                                M('volley_desc')->add(['user_id' => $userid, 'content' => '[完成任务] ' . $task['title'], 'price' => $task['reward'], 'types' => 1, 'time' => time()]);

                                M('user')->where(['id' => $userid])->setInc('volley', $task['reward']);
                            }
                        }*/

                        // 任务
                    //     D('Task')->finish('word_chat', $userid);
                    // }
                    $msg = $content;
                    break;
                case 1:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    if ($kefu == $userid || $kefu == $touserid) {
                        $chat_free = 1;
                    }

                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);
                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                //$touserConfig['chat_price'] = 0;

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }

                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }


                            if (!$free) {
                                if ($recharge_user['free_chat']) {
                                    /*$chatCount = M('chat_records')->where(['types' => $type, 'user_id' => $userid])->count();

                                    if ($chatCount >= $config['chat_count']) {
                                        exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                    } else {
                                        M('chat_records')->add(['types' => $type, 'user_id' => $userid, 'to_user' => $touserid, 'create_time' => time()]);

                                        $money = 0;
                                    }*/

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');
                                } else {
                                    // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                    $extra_recharge_rate = 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                if ($chat_scale && $chat_score) {
                                    $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                    $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, 'single' => $single, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, 'single' => $single, 'score' => 0];
                        }

                        /*if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }*/

                        /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'is_burn' => $is_burn, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'is_burn' => $is_burn, 'money' => $money, 'score' => 0];
                        }*/
                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'is_fate' => $fate, 'is_burn' => $is_burn, 'single' => $single, 'finish' => 1];
                    }

                    // 添加聊天
                    // $id = M('privatechat')->add($contain);

                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    $msg = '[图片]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, $type);
                    if ($userInfo['sex'] == '男' && $kefu != $userid_privacy && $kefu != $touserid_privacy) {
                        $userTopup = M('user_data')->where(['user_id'=>$userInfo['id']])->getField('topup');
                        if (!$userTopup || $userTopup <= 20) {
                            $check_hour = 2;
                            $check_num = 3;
                            $check_banned = 12;
                            // $hours1 = M('privatechat')->master(true)->where([
                            //     'userid'=>$userid_privacy,
                            //     'type'=>$type,
                            //     'addtime'=>['egt', date('Y-m-d H:i:s', strtotime('-'.$check_hour.' minutes'))]
                            // ])->limit($check_num)->count();
                            $hours1 =0;

                            if ($hours1 > $check_num - 1) {
                                M('warn_user_chat_records')->add([
                                    'user_id'=>$userid_privacy,
                                    'reason'=>$check_hour.'分钟内连发'.$check_num.'次以上图片 封号'.$check_banned.'小时',
                                    'content'=>'',
                                    'time'=>time()
                                ]);
                                if ($userInfo['is_banned'] != 1) {
                                    M('user')->where(['id'=>$userid])->save(['is_banned'=>1,'banned_end_time'=>date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours')), 'banned_desc'=>'系统检测账号异常']);
                                    M('config_personal')->where(['user_id'=>$userid])->save(['is_read_rule'=>0]);
                                    $userInfo['is_banned'] = 1;

                                    M('admin_logs')->add([
                                        'channel' => 3,
                                        'toward' => 0,
                                        'money' => 0,
                                        'user_id' => $userid,
                                        'content' => '短时间内发送多条图片信息,封禁账号至' . date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours'))
                                    ]);


                                    $auto_content = "系统检测账号异常，封禁账号至".date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours'));
                                    // $contain_tip = ['single' => 1, 'userid' => $kefu, 'touserid' => $userid, 'content' => $auto_content, 'finish' => 0, 'type'=>-3, 'data'=>json_encode(['type'=>1, 'content'=>'申请解除封号','state'=>0], JSON_UNESCAPED_UNICODE)];
                                }
                            }
                        }
                    }
                    break;
                case 2:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    if ($kefu == $userid || $kefu == $touserid) {
                        $chat_free = 1;
                    }

                    $singleFate = $single;
                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            $response = D('Privatechat')->checkFree($free, $money, $recharge_user, $userid);

                            if ($response['code'] != 200) {
                                exit(json_encode($response));
                            } else {
                                $free = $response['data']['free'];
                            }
                        }

                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }


                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                if ($chat_scale && $chat_score) {
                                    $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                    $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'single' => $single, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'single' => $single, 'score' => 0];
                        }

                        /*if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }*/

                        /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'score' => 0];
                        }*/

                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'single' => $single, "second" => $second, 'finish' => 1];

                        
                        if ($fate && $userInfo['sex'] == '女' && $userInfo['quality'] == 1) {
                            $contain['single'] = 2;
                            // $contain['id'] = M('privatechat')->order('id desc')->getField('id');
                            $singleFate = 2;
                        }
                    }

                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    $msg = '[语音]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $singleFate, $type);

                    if (!$fate && $userInfo['sex'] == '女' && $kefu != $userid_privacy && $kefu != $touserid_privacy) {
                        $check_hour = 5;
                        $check_num = 10;
                        // $hours1 = M('privatechat')->master(true)->where([
                        //     'userid'=>$userid_privacy,
                        //     'type'=>$type,
                        //     'addtime'=>['egt', date('Y-m-d H:i:s', strtotime('-'.$check_hour.' minutes'))],
                        //     'is_fate'=>0,
                        //     'front_id'=>['GT', 0]
                        // ])->limit($check_num)->count();
                        $hours1 =0;

                        if ($hours1 > $check_num - 1) {
                            $hasrecords = M('warn_user_chat_records')->master(true)->where([
                                'user_id'=>$userid_privacy,
                                'reason'=>$check_hour.'分钟内连发'.$check_num.'次以上语音',
                                'time'=>['egt', strtotime('-1 hours')]
                            ])->find();
                            if (!$hasrecords) {
                                M('warn_user_chat_records')->add([
                                    'user_id'=>$userid_privacy,
                                    'reason'=>$check_hour.'分钟内连发'.$check_num.'次以上语音',
                                    'content'=>'',
                                    'time'=>time()
                                ]);
                            }
                        }
                    }
                    break;
                case 3:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    if ($kefu != $userid && $kefu != $touserid) { // 非客服咨询
                        // 被动聊天不扣费
                        /*$chatFreeUser = M('chat_free')->where(['user_id' => $userInfo['id'], 'to_user' => $touserInfo['id']])->find();

                        if ($chatFreeUser) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') {
                                $greetRecords = M('greet_records')->where(['user_id' => $userInfo['id'], 'to_user' => $touserInfo['id']])->find();

                                if (!$greetRecords) {
                                    $chat_free = 1;
                                }
                            } else if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男') {
                                $greetRecords = M('greet_records')->where(['user_id' => $touserInfo['id'], 'to_user' => $userInfo['id']])->find();

                                if (!$greetRecords) {
                                    $chat_free = 1;
                                }
                            } else {
                                $chat_free = 1;
                            }
                        } else {
                            $chatFreeToUser = M('chat_free')->where(['user_id' => $touserInfo['id'], 'to_user' => $userInfo['id']])->find();

                            if (!$chatFreeToUser) {
                                $record = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $touserInfo['id'], 'touserid' => $userInfo['id']])->find();

                                if (!$record) {
                                    M('chat_free')->add(['user_id' => $touserInfo['id'], 'to_user' => $userInfo['id'], 'create_time' => time()]);
                                }
                            }
                        }*/
                    } else {
                        $chat_free = 1;
                    }

                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            $response = D('Privatechat')->checkFree($free, $money, $recharge_user, $userid);

                            if ($response['code'] != 200) {
                                exit(json_encode($response));
                            } else {
                                $free = $response['data']['free'];
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, "data" => json_encode(['cover' => I('cover')]), 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, "data" => json_encode(['cover' => I('cover')]), 'score' => 0];
                        }

                        /*if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }*/

                        /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "data" => json_encode(['cover' => I('cover')]), 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "data" => json_encode(['cover' => I('cover')]), 'money' => $money, 'score' => 0];
                        }*/
                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, "data" => json_encode(['cover' => I('cover')]), 'finish' => 1];
                    }

                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    $msg = '[视频]';

                    // 更新会话列表
                    //D('ChatLists')->updateLists($userid, $touserid, 0, 3);

                    break;
                case 6:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));
                    if ($kefu == $userid || $kefu == $touserid) {
                        $chat_free = 1;
                    }

                    $singleFate = $single;
                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            $response = D('Privatechat')->checkFree($free, $money, $recharge_user, $userid);

                            if ($response['code'] != 200) {
                                exit(json_encode($response));
                            } else {
                                $free = $response['data']['free'];
                            }
                        }

                        if (!$free && (!$intimate || !$intimate['intimate'])) {
                            $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                            if ($free) {
                                $touserConfig['chat_price'] = 0;
                            }
                        }


                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                if ($chat_scale && $chat_score) {
                                    $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                    $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'single' => $single, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'single' => $single, 'score' => 0];
                        }

                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'single' => $single, "second" => $second, 'finish' => 1];

                        
                        if ($fate && $userInfo['sex'] == '女' && $userInfo['quality'] == 1) {
                            $contain['single'] = 2;
                            // $contain['id'] = M('privatechat')->order('id desc')->getField('id');
                            $singleFate = 2;
                        }
                    }


                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    $msg = '[位置]';
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $singleFate, $type);
                    break;
                case 8:
                    $id = I('id');
                    $num = I('num');
                    $num = intval($num);

                    if ($num <= 0) exit(json_encode(['code' => 400, 'msg' => '数量有误']));

                    $gift = M('gift')->find($id);
                    if (!$gift) exit(json_encode(['code' => 400, 'msg' => '礼物类型不存在']));

                    if ($gift['types'] == 2) {
                        if (!$userInfo['noble_grade'] || $userInfo['noble_time'] < time()) {
                            exit(json_encode(['code' => 400, 'msg' => '需先开通VIP']));
                        }

                        $gradeNoble = M()->Query("SELECT * from grade_noble where FIND_IN_SET(6, privilege) order by grade asc limit 1");

                        if (!$gradeNoble) {
                            exit(json_encode(['code' => 400, 'msg' => '无权限']));
                        }

                        if ($userInfo['noble_grade'] < $gradeNoble[0]['grade']) {
                            exit(json_encode(['code' => 400, 'msg' => '需先开通' . $gradeNoble[0]['name'] . 'VIP或以上等级的VIP']));
                        }
                    }

                    if ($touserInfo['is_banned']) {
                    // if ($touserInfo['is_banned'] && strtotime($touserInfo['banned_end_time']) > time()) {
                        exit(json_encode(['code' => 400, 'msg' => '送礼失败']));
                    }

                    $money = $gift['price'] * $num;

                    $time = time();
                    $number = date('YmdHis') . mt_rand(1000, 9999);

                    //$volley = M('user')->where(['id' => $userid])->getField('volley');
                    $volley = $userInfo['volley'];
                    $volley_gift = $userInfo['volley_gift'];
                    $volley_real = $userInfo['volley'] - $userInfo['volley_gift'];
                    $score = $money;
                    if ($userInfo['sex'] == '男') {
                        if ($volley_gift) {
                            $score = $money - ($money>$volley_gift?$volley_gift:$money);
                        }
                        if ($volley < $money) exit(json_encode(['code' => 400, 'msg' => '余额不足']));
                    } else {
                        if ($userInfo['beans'] < $money) exit(json_encode(['code' => 400, 'msg' => '豆豆不足']));
                    }

                    $datetime = date('Y-m-d');
                    // $todaysend = M('privatechat')->where(['type'=>8, 'userid'=>$userid_privacy, 'touserid'=>$touserid_privacy])->where(['addtime'=>['like', $datetime . '%']])->select();
                    // $sendnum = 0;
                    // foreach ($todaysend as $key => $value) {
                    //     $tmp = json_decode($value['data'],true);
                    //     $sendnum += $tmp['money'];
                    // }
                    // if($sendnum + $money > 2000){
                    //     exit(json_encode(['code' => 400, 'msg' => '今日送对方礼物已达上限']));
                    // }
                    // if($sendnum + $num > 2){
                    //     exit(json_encode(['code' => 400, 'msg' => '每日只能送对方两个礼物']));
                    // }

                    $contain = [
                        "userid" => $userid_privacy,
                        "touserid" => $touserid_privacy,
                        "type" => $type,
                        "content" => '[礼物]',
                        'money' => $money,
                        'score' => $score * 1,
                        'is_fate' => $money>0?0:($recharge_user['id'] == $userInfo['id'] && $userInfo['entertainment'] == 1 ? 0 : 1),
                        'finish' => 1,
                        'front_id' => time(),
                        'is_public' => $is_public,
                    ];
                    if ($money) {
                        $gift_json_data = ['money' => $money, 'id' => $id, 'cover' => $gift['cover'], 'num' => $num, 'name' => $gift['name'], 'u_d_id'=>$userInfo_privacy['device_id'], 'payer'=>$userid_privacy,'preview'=>$gift['preview'],'videourl'=>$gift['videourl'],'videojson'=>$gift['videojson']];
                    } else {
                        $gift_json_data = ['money' => $money, 'id' => $id, 'cover' => $gift['cover'], 'num' => $num, 'name' => $gift['name'], 'u_d_id'=>$userInfo_privacy['device_id'],'preview'=>$gift['preview'],'videourl'=>$gift['videourl'],'videojson'=>$gift['videojson']];
                    }
                    $contain['data'] = json_encode($gift_json_data, JSON_UNESCAPED_UNICODE);

                    $singleGift = 0;
                    // 添加聊天
                    if ($timing == 1 && $userInfo['sex'] == '女' && $userInfo['quality'] == 1 && $money <= 0) {
                        // $contain['id'] = M('privatechat')->order('id desc')->getField('id');
                        $contain['single'] = 2;
                        $singleGift = 2;
                    }

                    if ($timing == 1) {
                        $todaySendCount = M('privatechat')->where(["userid" => $userid_privacy,"touserid" => $touserid_privacy,"type" => $type,"content" => '[礼物]','money' => 0, 'addtime'=>['egt', date('Y-m-d') . ' 00:00:00']])->count();
                        if ($todaySendCount >= 2) exit(json_encode(['code' => 400, 'msg' => '今日向对方打招呼已达上限']));
                    }
                    $id = M('privatechat')->add($contain);
                    $contain['id'] = $id;
                    $contain['send_sex'] = $userInfo['sex'];
                    $TencentIMResponse = (new TencentIM)->sendmsg($contain['userid'], $contain['touserid'], $contain['content']??'', $contain, $contain['single']??0);
                    $gift_json_data['MsgKey'] = $TencentIMResponse['MsgKey']??'';
                    $contain['data'] = json_encode($gift_json_data, JSON_UNESCAPED_UNICODE);
                    M('privatechat')->save($contain);

                    $pushNewMsgs[] = $contain;


                    M('gift_record')->add([
                        'num' => $num,
                        'gift_id' => $gift['id'],
                        'user_id' => $userid,
                        'to_user' => $touserid,
                    ]);
                    // 检查用户性别
                    if ($userInfo['sex'] == '女') {
                        $score = 0;
                        D('VolleyDesc')->beans($userid, $money * 1, '给' . $touserInfo_privacy['name'] . '(' . $touserInfo_privacy['id'] . ')赠送礼物：' . $gift['name'] . ' X ' . $num);
                    }else{
                    if ($money > 0) {
                        // 扣除余额
                        D('VolleyDesc')->index($userid, $money * 1, '给' . $touserInfo_privacy['name'] . '(' . $touserInfo_privacy['id'] . ')赠送礼物：' . $gift['name'] . ' X ' . $num);

                        // 创建订单
                        M('order_common')->add([
                            'number' => $number,
                            'user_id' => $userid,
                            'money' => $money,
                            'status' => 1,
                            'types' => 4,
                            'data' => json_encode(['id' => $id, 'touserid' => $touserid, 'num' => $num]),
                            'create_time' => $time,
                            'update_time' => $time,
                        ]);

                        if ($intimate) {
                            M('user_intimate')->where(['id' => $intimate['id']])->save([
                                $field_count => $intimate[$field_count] + $money,
                                'intimate' => $intimate['intimate'] + $money * 1,
                                'update_time' => time(),
                                'unshow'=>$money>0?0:$intimate['unshow']
                            ]);
                        } else {
                            M('user_intimate')->add([
                                'couple_a' => $couple_a,
                                'couple_b' => $couple_b,
                                $field_count => $money,
                                'intimate' => $money * 1,
                                'create_time' => time(),
                                'update_time' => time()
                            ]);
                        }

                        M('user')->where(['id' => $touserid])->setInc('charm_value', $money * 1);

                        // 榜单记录
                        /*$records_types = $touserInfo['sex'] == '女' ? '1,2,3,6' : '1,3,4,6';
                        D('RankingRecords')->index($records_types, $userid, $touserid, $money);*/



                        // $giftsum = M('order_common')->master(true)->where(['user_id' => $userid, 'data'=>['like', '%"touserid":"'.$touserid.'","num"%'], 'status'=>1])->sum('money');
                        // if($giftsum >= 2000){
                        //     $tipContent = '平台不存在送礼物解锁联系方式以及解锁免费聊天权限的功能，请你知悉。';
                        //     $tipcontain = ["userid" => $touserid_privacy, "touserid" => $userid_privacy, "type" => -1, 'single' => 1, "content" => $tipContent, 'isRead' => 1, 'finish' => 1];
                        //     $pushNewMsgs[] = $tipcontain;
                        // }

                    }
                    if ($score) {
                        // 分成
                        $fencheng_content = '收获' . $userInfo_privacy['name'] . '(' . $userInfo_privacy['id'] . ')赠送的礼物：' . $gift['name'] . 'X' . $num;

                        D('User')->fencheng($touserid, $userid, $score * 1, 'gift', $fencheng_content);
                    }
                    }
                    $msg = '[礼物]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $singleGift, 8);

                    break;
                case 11:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    $content = intval($content);

                    $where = [
                        'id' => $content,
                        'is_hidden' => 0,
                    ];
                    $sticker = M('chat_sticker')->field('image')->where($where)->find();
                    if (!$sticker) {
                        exit(json_encode(['code' => 400, 'msg' => '表情不存在或已下线']));
                    } else {
                        $content = $sticker['image'];
                    }


                    $extraMoney = 0;

                    if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                    } else {
                        $chat_free = 1;
                    }

                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);

                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                //$touserConfig['chat_price'] = 0;

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }

                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }


                            if (!$free) {
                                if ($recharge_user['free_chat']) {

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                    $free = 1;
                                } else {
                                    // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                    $extra_recharge_rate = 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "data" => $data, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "data" => $data, "content" => $content, 'money' => $money, 'score' => 0];
                        }

                    } else {
                        if ($userInfo['sex'] == '女' && $userInfo['quality'] == 1) {
                            $single = 2;
                        }
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "data" => $data, "content" => $content, 'is_fate' => $fate, "single" => $single, 'finish' => 1];
                    }
                    
                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;
                    
                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 11, $content, 0, $userInfo['sex']);

                    // if ($userid != $kefu && !$greet && !$notice) {
                        // 任务
                    //     D('Task')->finish('word_chat', $userid);
                    // }
                    $msg = '[表情]';
                    break;
                case 12:
                    if ($content == '') exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                        // 敏感词检测
                        $contain = M('filter_word')->cache(true)->where(['state' => 1])->getField('name', true);
                        foreach ($contain as $k => $v) {
                            if (stripos($content, $v) !== false) {
                                exit(json_encode(['code' => 400, 'msg' => '消息含有敏感词"' . $v . '",请重新编辑发送']));
                            }
                        }

                        $extraMoney = 0;

                        if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                            /*if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $touserInfo['is_identity_authentication'] == 2) {
                                $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $userid, 'touserid' => $touserid])->find();
                                if (!$chatRecord) {
                                    $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $touserid, 'touserid' => $userid])->order('id desc')->find();
                                    if ($chatRecord) {
                                        $extraMoney = 1;
                                    }
                                }
                            }*/
                        } else {
                            $chat_free = 1;
                        }

                        if (!$chat_free) {
                            if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                                $money = $touserConfig['chat_price'];

                                if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                    $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                    if ($gradeNoble) {
                                        $privilege = explode(',', $gradeNoble['privilege']);

                                        if (in_array(10, $privilege)) {
                                            $privilegeValue = explode(',', $gradeNoble['value']);

                                            if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                                $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                                $privilegeValue[0] = intval($privilegeValue[0]);

                                                if ($privilegeValue[0] > $userCount) {
                                                    M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                    //$touserConfig['chat_price'] = 0;

                                                    $free = 1;
                                                }
                                            }
                                        }
                                    }
                                }

                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }


                                if (!$free) {
                                    if ($recharge_user['free_chat']) {
                                        /*$chatCount = M('chat_records')->where(['types' => $type, 'user_id' => $userid])->count();

                                        if ($chatCount >= $config['chat_count']) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            M('chat_records')->add(['types' => $type, 'user_id' => $userid, 'to_user' => $touserid, 'create_time' => time()]);

                                            $money = 0;
                                        }*/

                                        M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                        $free = 1;
                                    } else {
                                        // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                        $extra_recharge_rate = 0;
                                        if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                            if ($recharge_user['id'] == $userid) {
                                                exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                            } else {
                                                exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                            }
                                        }
                                    }
                                }
                            }

                            $money = $free ? 0 : $money;
                            if ($chat_scale && $money) {
                                $money = $money * $chat_scale['scale'] / 100;
                                $money = $money < 0.1 ? 0.1 : $money;
                            }

                            if ($recharge_user['id'] == $userid) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                                } else {
                                    $chat_score = $money;
                                }

                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                            } else {
                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }

                            /*if ($recharge_user['id'] == $userid) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }*/

                            /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => ($chat_score + $extraMoney) * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }*/
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'finish' => 1, 'single' => $single];
                        }

                        if($data){
                            $contain['data'] = $data;
                        }else{
                            exit(json_encode(['code' => 400, 'msg' => '操作错误']));
                        }
                        
                        // 添加聊天
                        // $id = M('privatechat')->add($contain);
                        // $contain['id'] = $id;
                        $pushNewMsgs[] = $contain;
                        
                        // 更新会话列表
                        D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, $content, 0, $userInfo['sex']);


                        // 男性 客服自动回复
                        if ($userInfo['sex'] == '男' && $kefu == $touserid) {
                            $auto_customer_service = 0;

                            $customer_service_chat = M('customer_service_chat')->where(['user_id' => $userid])->find();
                            if ($customer_service_chat) {
                                if (($customer_service_chat['create_time'] + 3600) < time()) {
                                    $auto_customer_service = 1;
                                    M('customer_service_chat')->where(['id' => $customer_service_chat['id']])->setField('create_time', time());
                                }
                            } else {
                                $auto_customer_service = 1;
                                M('customer_service_chat')->add(['user_id' => $userid, 'create_time' => time()]);
                            }

                            // if ($auto_customer_service) {
                            //     $auto_content = "由于用户群体比较大，人工客服只能处理身份审核以及突发事件，如需举报，投诉可去用户资料页去投诉用户，如需联系平台，可以去留言。感谢你的支持";
                            //     $contain = ['single' => 1, 'userid' => $touserid, 'touserid' => $userid, 'content' => $auto_content, 'finish' => 1];
                            //     // $id = M('privatechat')->add($contain);
                            //     // $contain['id'] = $id;
                            //     $pushNewMsgs[] = $contain;

                            //     // 更新会话列表
                            //     D('ChatLists')->updateLists($touserid, $userid, 1, 0, $auto_content);
                            // }
                        }


                        // 提醒词记录
                        if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男' && $kefu != $userid && $kefu != $touserid) {
                            $warnWord = M('chat_tip_word')->where(['is_hidden' => 0, 'sex'=>['in', ['均可', $userInfo['sex']]]])->cache(true, 5)->getField('id, title, single, content');
                            foreach ($warnWord as $k => $v) {
                                if ($v['title']=='*' && $sysMask) continue;
                                if (stripos($content, $v['title']) !== false) {
                                    $contain = ['type' => -1, 'single' => $v['single'], 'userid' => $userid_privacy, 'touserid' => $touserid_privacy, 'content' => $v['content'], 'finish' => 1];
                                    // $id = M('privatechat')->add($contain);
                                    // $contain['id'] = $id;
                                    $pushNewMsgs[] = $contain;

                                    $isWarnWord = 1;

                                    //$this->getNewMsg(json_encode(['userid' => $userid, 'touserid' => $touserid, 'type' => -1]));
                                    break;
                                }
                            }
                        }


                    // if ($userid != $kefu && !$greet && !$notice) {
                    //     // 任务
                    //     D('Task')->finish('word_chat', $userid);
                    // }
                    $msg = $content;
                    break;
                case 13:
                    $extraMoney = 0;

                    if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                    } else {
                        $chat_free = 1;
                    }

                    $hflen = 0;
                    $hfnum = 0;
                    while(!$hflen){
                        if(S('heartfeltsLimit:' . $userid_privacy)){
                            exit(json_encode(['code'=>201, 'msg'=>'发送过于频繁，请稍后再试']));
                        }
                        $hfnum++;
                        if($hfnum>3){
                            exit(json_encode(['code'=>201, 'msg'=>'请稍后再试']));
                        }
                        $heartfeltsCache = S('heartfelts:' . $userid_privacy);
                        $heartfeltsWhere = [];
                        if($heartfeltsCache){
                            $heartfeltsCache = explode(',', $heartfeltsCache);
                            $heartfeltsWhere['id'] = ['not in', $heartfeltsCache];
                        }else{
                            $heartfeltsCache = [];
                        }
                        $heartfelts = M('chat_heartfelt')->where($heartfeltsWhere)->select();
                        $hflen = sizeof($heartfelts);
                        if(!$hflen){
                            S('heartfeltsLimit:' . $userid_privacy, time(), 60);
                            S('heartfelts:' . $userid_privacy, null);
                        }else{
                            $hfitem = $heartfelts[rand(0, $hflen - 1)];
                            array_push($heartfeltsCache, $hfitem['id']);
                            S('heartfelts:' . $userid_privacy, implode(',', $heartfeltsCache), 120);
                        }
                    }


                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);

                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }


                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }

                            if (!$free) {
                                if ($recharge_user['free_chat']) {

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                    $free = 1;
                                } else {
                                    // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                    $extra_recharge_rate = 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $hfitem['title'], 'data' => $hfitem['content'], 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $hfitem['title'], 'data' => $hfitem['content'], 'money' => $money, 'score' => 0];
                        }

                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $hfitem['title'], 'data' => $hfitem['content'], 'finish' => 1, 'single' => $single];
                    }
                    
                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;
                    
                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, $hfitem['title'], 0, $userInfo['sex']);


                    $msg = $hfitem['title'];
                    break;
                case 14:
                    $extraMoney = 0;
                    if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                    } else {
                        $chat_free = 1;
                    }

                    $chat = M('privatechat')->master(true)->where(['id'=>$content])->find();
                    if($chat['state'] == 3){
                        exit(json_encode(['code'=>201, 'msg'=>'已经回答过该问题']));
                    }
                    if($chat['userid'] == $userid_privacy){
                        if($chat['state'] == 1){
                            exit(json_encode(['code'=>201, 'msg'=>'已经回答过该问题']));
                        }
                    }elseif($chat['state'] == 2){
                        exit(json_encode(['code'=>201, 'msg'=>'已经回答过该问题']));
                    }

                    $state = $chat['state'] ? 3 : ($chat['userid'] == $userid_privacy ? 1 : 2);
                    $answer = json_decode($chat['data'], true);
                    if($answer && isset($answer[$data])){
                        $answer = $answer[$data];
                    }else{
                        exit(json_encode(['code'=>201, 'msg'=>'操作错误']));
                    }

                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);

                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }


                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }

                            if (!$free) {
                                if ($recharge_user['free_chat']) {

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                    $free = 1;
                                } else {
                                    // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                    $extra_recharge_rate = 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '问:'.$chat['content'].'<br />答:'.$answer, 'order_id' => $chat['id'], 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '问:'.$chat['content'].'<br />答:'.$answer, 'order_id' => $chat['id'], 'money' => $money, 'score' => 0];
                        }

                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '问:'.$chat['content'].'<br />答:'.$answer, 'order_id' => $chat['id'], 'finish' => 1, 'single' => $single];
                    }
                    
                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    M('privatechat')->where(['id'=>$chat['id']])->setField('state', $state);
                    
                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, '问:'.$chat['content'].'<br />答:'.$answer, 0, $userInfo['sex']);


                    $msg = '问:'.$chat['content'].'<br />答:'.$answer;
                    break;
                case 15:
                    $extraMoney = 0;
                    if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                    } else {
                        $chat_free = 1;
                    }
                    $ChatScriptBox = [];
                    $num = 0;
                    while(sizeof($ChatScriptBox) < 6){
                        $csbWhere = sizeof($ChatScriptBox) ? ['id'=>['not in', array_column($ChatScriptBox, 'id')]] : [];
                        $csb = M('chat_script_box')->where('rand()')->where($csbWhere)->limit(6 - sizeof($ChatScriptBox))->select();
                        $ChatScriptBox = array_merge($ChatScriptBox, $csb);
                        $num++;
                        if($num>10){
                            exit(json_encode(['code'=>201, 'msg'=>'服务器繁忙，请稍后再试']));
                        }
                    }
                    $ChatScriptBox = array_column($ChatScriptBox, 'content');
                    $ChatScriptBox = json_encode($ChatScriptBox, JSON_UNESCAPED_UNICODE);

                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);

                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }


                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }

                            if (!$free) {
                                if ($recharge_user['free_chat']) {

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                    $free = 1;
                                } else {
                                    // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                    $extra_recharge_rate = 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '快和我一起来摇骰子吧', 'data'=>$ChatScriptBox,  'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '快和我一起来摇骰子吧', 'data'=>$ChatScriptBox,  'money' => $money, 'score' => 0];
                        }

                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '快和我一起来摇骰子吧', 'data'=>$ChatScriptBox,  'finish' => 1, 'single' => $single];
                    }
                    
                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    M('privatechat')->where(['id'=>$chat['id']])->setField('state', $state);
                    
                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, '快和我一起来摇骰子吧', 0, $userInfo['sex']);


                    $msg = '快和我一起来摇骰子吧';
                    break;
                case 16:
                    $extraMoney = 0;
                    if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                    } else {
                        $chat_free = 1;
                    }


                    $chat = M('privatechat')->master(true)->where(['id'=>$content, 'touserid'=>$userid_privacy, 'state'=>0])->find();
                    if(!$chat){
                        exit;
                    }

                    $answer = json_decode($chat['data'], true);

                    $pubrand = rand(1,6);
                    $subrand = rand(1,6);
                    $randsum = $pubrand + $subrand;
                    switch($randsum){
                        case 2:
                        case 12:
                            $answerIdx = 0;
                            break;
                        case 3:
                        case 11:
                            $answerIdx = 1;
                            break;
                        case 4:
                        case 10:
                            $answerIdx = 2;
                            break;
                        case 5:
                        case 9:
                            $answerIdx = 3;
                            break;
                        case 6:
                        case 8:
                            $answerIdx = 4;
                            break;
                        default:
                            $answerIdx = 5;
                    }


                    $pushNewMsgs[] = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => 17, "content" => $subrand, 'finish' => 1, 'score' => 0];
                    $pushNewMsgs[] = ["userid" => $touserid_privacy, "touserid" => $userid_privacy, "type" => 17, "content" => $pubrand, 'finish' => 1, 'score' => 0];

                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);

                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }

                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }


                            if (!$free) {
                                if ($recharge_user['free_chat']) {

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                    $free = 1;
                                } else {
                                    // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                    $extra_recharge_rate = 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '点数之和是' . $randsum . '，请' . $answer[$answerIdx], 'money' => $money, 'score' => $chat_score * 1, 'order_id' => $content];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '点数之和是' . $randsum . '，请' . $answer[$answerIdx], 'money' => $money, 'score' => 0, 'order_id' => $content];
                        }

                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '点数之和是' . $randsum . '，请' . $answer[$answerIdx], 'finish' => 1, 'single' => $single, 'order_id' => $content];
                    }
                    
                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    M('privatechat')->where(['id'=>$chat['id']])->setField('state', 1);
                    
                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, '点数之和是' . $randsum . '，请' . $answer[$answerIdx], 0, $userInfo['sex']);


                    $msg = '点数之和是' . $randsum . '，请' . $answer[$answerIdx];
                    break;

                case 18:
                    $contain = [
                        "userid" => $userid_privacy,
                        "touserid" => $touserid_privacy,
                        "type" => $type,
                        "content" => '[礼物]',
                        'finish' => 1,
                        "data" => $data,
                        'front_id' => time(),
                    ];

                    $pushNewMsgs[] = $contain;

                    $msg = '[礼物]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, $type, $contain['content']);

                    break;
                case 19:
                    $contain = [
                        "userid" => $userid_privacy,
                        "touserid" => $touserid_privacy,
                        "type" => $type,
                        "content" => '[商品代付]请你帮我付个款吧',
                        'finish' => 1,
                        "data" => $data,
                        'front_id' => time(),
                    ];

                    $pushNewMsgs[] = $contain;

                    $msg = '[礼物]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, $type, $contain['content']);

                    break;
                case 20:
                    $contain = [
                        "userid" => $userid_privacy,
                        "touserid" => $touserid_privacy,
                        "type" => $type,
                        "content" => '[征婚]'.$content,
                        'finish' => 1,
                        "data" => $data,
                        'front_id' => time(),
                    ];

                    $pushNewMsgs[] = $contain;

                    $msg = '[征婚]'.$content;

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, $type, $contain['content']);

                    break;
                case 21:
                    $contain = [
                        "userid" => $userid_privacy,
                        "touserid" => $touserid_privacy,
                        "type" => $type,
                        "content" => $content,
                        'finish' => 1,
                        "data" => $data,
                        'front_id' => $front_id?:time(),
                    ];

                    $pushNewMsgs[] = $contain;

                    $msg = $content;

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, $type, $contain['content']);

                    break;
                case 22:
                    $contain = [
                        "userid" => $userid_privacy,
                        "touserid" => $touserid_privacy,
                        "type" => $type,
                        "content" => $content,
                        'single' => $single,
                        'finish' => 1,
                        "data" => $data,
                        'front_id' => time(),
                    ];

                    $pushNewMsgs[] = $contain;

                    $msg = '[盲盒消息]'.$content;

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, $type, $contain['content'], 3);

                    break;
                default:
                    exit(json_encode(['code' => 400, 'msg' => '操作错误']));
            }
            M()->startTrans();
            if (!$system_greet) {
                if (!in_array($kefu, [$userid, $touserid]) || !$greet) {
                    if (!in_array($type, [8, 9, 10])) {
                        if (!$free && ($money + 0)) {
                            if ($recharge_user['id'] == $userid || !$chat_free) {
                                $recharge_msg = $recharge_user['id'] == $userid ? '给' . $touserInfo_privacy['name'] . '(' . $touserInfo_privacy['id'] . ')发消息扣金币' : $userInfo_privacy['name'] . '(' . $userInfo_privacy['id'] . ')发消息扣金币';
                                // 扣除余额
                                $IncOk = D('VolleyDesc')->index($recharge_user['id'], $money, $recharge_msg);
                            }else{
                                $IncOk = true;
                            }
                        }else{
                            $IncOk = true;
                        }
                    }else{
                        $IncOk = true;
                    }

                    if($recharge_user['id'] != $userid){


                        $scoreChat = M('privatechat')->master(true)->where(['userid' => $touserid_privacy, 'touserid' => $userid_privacy, 'score' => ['gt', 0], 'finish' => 0])->select();

                        $ids = array_column($scoreChat, 'id');
                        if (sizeof($ids)) {
                            
                            foreach ($ids as $val){
                                M('privatechat')->where(['id' => $val])->save(['finish' => 1]);
                            }
                            // M('privatechat')->where(['id' => ['in', $ids]])->save(['finish' => 1]);
                            // $chats = M('privatechat')->where(['id' => ['in', $ids]])->select();
                            // foreach ($chats as $key => $value) {
                            //     $MsgKey = json_decode($value['data'], true)['MsgKey'];
                            //     (new TencentIM)->modify_c2c_msg($userid_privacy, $touserid_privacy, $MsgKey, json_encode($value, true));
                            // }
                        }
                        $scoreData = [];
                        $scoreUpdate = 0;

                        $content = '回复' . $touserInfo_privacy['name'] . '(' . $touserInfo_privacy['id'] . ')的消息获得积分';

                        foreach ($scoreChat as $item) {
                            if (!in_array($item['type'], [8, 9, 10])) {
                                $money = $item['score'];
                            } else {
                                $money = 0;
                            }

                            $scoreData[] = [
                                'uid' => $userid,
                                'touid' => $touserid,
                                'content' => $content,
                                'money' => $money,
                                'type' => 1,
                                'time' => time(),
                            ];

                            $scoreUpdate += $money;
                        }

                        if ($scoreUpdate) {

                            // if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '女') {

                            // } else {
                                // 榜单记录
                                //D('RankingRecords')->index(1, $userid, $touserid, $scoreUpdate * 10);

                                foreach ($scoreData as $value) {
                                    if($value['money']){
                                        // 分成
                                        D('User')->fencheng($userid, $touserid, $value['money'], 'chat', $content);
                                    }
                                }

                                //M('yaoqing_records')->addAll($scoreData);
                                //M('user')->where(['id' => $userid])->setInc('score', $scoreUpdate);
                                M('user')->where(['id' => $userid_privacy])->setInc('charm_value', $scoreUpdate);
                            // }


                            // 亲密度
                            if ($intimate) {
                                M('user_intimate')->where(['id' => $intimate['id']])->save([
                                    $field_count => $intimate[$field_count] + $scoreUpdate * 10,
                                    'intimate' => $intimate['intimate'] + $scoreUpdate,
                                    'update_time' => time(),
                                    'unshow'=>$scoreUpdate>0?0:$intimate['unshow']
                                ]);
                            } else {
                                M('user_intimate')->add([
                                    'couple_a' => $couple_a,
                                    'couple_b' => $couple_b,
                                    $field_count => $scoreUpdate * 10,
                                    'intimate' => $scoreUpdate,
                                    'create_time' => time(),
                                    'update_time' => time()
                                ]);
                            }
                            /*$intimate = M('user_intimate')->where(['couple_a' => $couple_a])->find();

                            $result = M('user_defend')->where(['user_id' => $touserid, 'to_user' => $userid])->find();

                            if (!$userInfo['angel']) {

                                $types = $userInfo['sex'] == '女' ? 2 : 1;
                                $gradeCharm = M('grade_charm')->where(['types' => $types, 'min' => ['elt', $userInfo['charm_value']]])->order('grade desc')->getField('grade');

                                //$gift_money = $userInfo['sex'] == '女' ? $gradeCharm * 100 : $gradeCharm * 20;

                                if ($userInfo['sex'] == '女') {
                                    $gift_money = $gradeCharm * $config['female_times'];
                                    if ($gift_money < $config['female_min']) {
                                        $gift_money = $config['female_min'];
                                    }
                                } else {
                                    $gift_money = $gradeCharm * $config['male_times'];
                                    if ($gift_money < $config['male_min']) {
                                        $gift_money = $config['male_min'];
                                    }
                                }

                                $hadMoney = $userid > $touserid ? $intimate['count_a'] : $intimate['count_b'];

                                $mustMoney = $gift_money - ($hadMoney - $money);

                                $isAngel = 0;
                                if ($mustMoney <= $money) {
                                    $isAngel = 1;
                                } else {
                                    $gradeDefend = M('grade_defend')->where(['min' => ['elt', $hadMoney]])->order('grade desc')->find();

                                    if ($gradeDefend) {
                                        $isAngel = 1;
                                    }
                                }

                                if ($isAngel) {
                                    M('user')->where(['id' => $userid])->setField('angel', $touserid);
                                    M('user_defend')->where(['user_id' => ['neq', $touserid], 'to_user' => $userid])->save(['angel' => 0, 'update_time' => $update_time]);

                                    $isAngel = 1;
                                    $update_time = time();
                                } else {
                                    $isAngel = 0;
                                    $update_time = $result ? $result['update_time'] : time();
                                }

                                $defend_money = $hadMoney;
                            } else {
                                $angel = M('user_defend')->where(['to_user' => $userid, 'angel' => 1])->find();

                                if (($angel['money'] < $result['money']) && $angel['user_id'] != $touserid) {

                                    M('user')->where(['id' => $userid])->setField('angel', $touserid);
                                    M('user_defend')->where(['user_id' => ['neq', $touserid], 'to_user' => $userid])->save(['angel' => 0, 'update_time' => $update_time]);

                                    $isAngel = 1;
                                    $update_time = time();
                                } else {
                                    $isAngel = 0;
                                    $update_time = $angel['update_time'];
                                }

                                $defend_money = $result['money'];
                            }

                            if ($result) {
                                M('user_defend')->where(['id' => $result['id']])->save(['angel' => $isAngel, 'money' => $defend_money, 'update_time' => $update_time]);
                            } else {
                                M('user_defend')->add([
                                    'user_id' => $touserid,
                                    'to_user' => $userid,
                                    'money' => $defend_money,
                                    'angel' => $isAngel,
                                    'create_time' => time(),
                                    'update_time' => time(),
                                ]);
                            }*/
                        }


                    } else if ($userInfo['sex'] == '女' && $touserid_privacy != $kefu && $userInfo['id'] != $kefu) {
                        $msg_1 = "当前聊天是你付费，如要改成对方付费请点击右下方'+'->'换TA付费'按钮";
                        $contain = ["userid" => $touserid_privacy, "touserid" => $userid_privacy, "type" => -1, "content" => $msg_1, 'finish' => 1, 'single' => 1];
                        $hasTip = M('privatechat')->where($contain)->where(['addtime'=>['gt',date('Y-m-d H:i:s', strtotime('-1 hours'))]])->find();
                        if (!$hasTip) {
                            $pushNewMsgs[] = $contain;
                        }
                    }

                    //---------------------------

                    // 魅力值
                    if ($money + 0) {
                        M('user')->where(['id' => $userid_privacy])->setInc('tycoon', $money * 1);
                    }
                }else{
                    $IncOk = true;
                }
            }else{
                $IncOk = true;
            }
            if($type != 8){
                $pushNewMsgs[0]['front_id'] = $front_id;
            }
            $payer_id = $recharge_user['id'] == $userid ? $userid_privacy : $touserid_privacy;
            foreach ($pushNewMsgs as $pmk => $pmv) {
                $pushNewMsgs[$pmk]['up'] = 0;
                if(isset($pmv['id']) && $type != 8){
                    if(!isset($pmv['type'])){
                        $pushNewMsgs[$pmk]['type'] = 0;
                    }
                    $pushNewMsgs[$pmk]['up'] = 1;
                    continue;
                }
                if($type == 8 && $pmk == 0){
                    continue;
                }

                $user_device_id_key = $pmv['userid'] == $userid_privacy?'u_d_id':'t_d_id';
                if (isset($pmv['data']) && $pmv['data'] && strpos($pmv['data'], '{') === 0) {
                    $pmv['data'] = json_decode($pmv['data'], true);
                    $pmv['data'][$user_device_id_key] = $userInfo_privacy['device_id'];
                    $chat_data_o = $pmv['data'];
                } else if (isset($pmv['data']) && $pmv['data']) {
                    $chat_data_o = [$user_device_id_key => $userInfo_privacy['device_id'], 'value'=>$pmv['data']];
                } else {
                    $chat_data_o = [$user_device_id_key => $userInfo_privacy['device_id']];
                }

                if (isset($pmv['score']) && $pmv['score']) {
                    if ($userInfo['volley_gift']>0) {
                        $use_volley_gift = $pmv['score'] > $userInfo['volley_gift'] ? $userInfo['volley_gift'] : $pmv['score'];
                        $pmv['score'] = $pmv['score'] - $use_volley_gift;
                        $userInfo['volley_gift']-=$use_volley_gift;
                    }
                    $chat_data_o['payer'] = $payer_id;
                }

                $pmv['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                $pmv['send_sex'] = $userInfo['sex'];
                $pmv['ip'] = getClientIP();
                $msgid = M('privatechat')->add($pmv);
                $pushNewMsgs[$pmk]['id'] = $msgid;
                $pmv['id'] = $msgid;
                $TencentIMResponse = (new TencentIM)->sendmsg($pmv['userid'], $pmv['touserid'], $pmv['content']??'', $pmv, $pmv['single']??0);
                $chat_data_o['MsgKey'] = $TencentIMResponse['MsgKey']??'';
                $pmv['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                M('privatechat')->save($pmv);
            }
            // if ($privatechat_free && $chat_free) {
            //     $chatfreeSeeder = $privatechat_free['server'] == $userid ? 'seller_msg' : 'buyer_msg';
            //     M('privatechat_free')->where(['id'=>$privatechat_free['id']])->setInc($chatfreeSeeder);
            // }
            if($IncOk){
                M()->commit();
            }else{
                M()->rollback();
                exit(json_encode(['code' => 400, 'msg' => '服务繁忙']));
            }

            if(in_array($type, [0, 12, 20, 22])){
                // 预警词记录
                if ($kefu != $userid && $kefu != $touserid_privacy) {
                    $warnWord = M('chat_warn_word')->where(['is_hidden' => 0])->cache(true)->getField('id, title');
                    foreach ($warnWord as $k => $v) {
                        if (stripos($pushNewMsgs[0]['content'], $v) !== false) {
                            M('chat_warn')->add(['user_id' => $userid_privacy, 'word_id' => $k, 'chat_id' => $pushNewMsgs[0]['id'], 'create_time' => time()]);
                            break;
                        }
                    }
                }
            }

            // 清除聊天缓存
            // S("getMsgList$userid&$touserid",null);
            // S("getMsgList$touserid&$userid",null);



            if ($userid != $kefu && !$greet && !$notice && in_array($type, [0, 12])) {
                // 任务
                D('Task')->finish('word_chat', $userid);
            }

            if(!$system_greet) {

                foreach ($pushNewMsgs as $pmk => $pmv) {
                    if ($pmv['up'] == 1) continue;
                    // if ($pmv['single'] == 2) {
                    //     $pushNewMsgs[$pmk]['single'] = 0;
                    // }
                    $pmv['payer_id'] = $payer_id;
                    $this->pushNewMsg($pmv);
                }
                // $this->getNewMsg(json_encode(['userid' => $userid, 'touserid' => $touserid]));
                $this->getOtherList(json_encode(['userid' => $touserid_privacy, 'count' => '', 'type' => '']));
                // 推送
                if(!$touserInfo['unpush'] && (!isset($pushNewMsgs[0]['single']) || $pushNewMsgs[0]['single'] != 2)){
                    $datas = json_encode(['type' => 2, 'userid' => $userid_privacy, 'name' => $userInfo_privacy['name'], 'privacy'=> $userInfo_privacy['reg'] == 2 ? 1 : 0], JSON_UNESCAPED_UNICODE);
                    D('Push')->send(2, $touserid, $userInfo_privacy['name'], $msg, $datas);
                }
                if (!$timing && !$fate && $userid != $kefu && $touserid != $kefu && $touserInfo['sex'] == '女' && $userInfo['sex'] == '男') {
                    $hasWelFare = M('welfare')->master(true)->where(['user_id'=>$touserid, 'state'=>1])->find();
                    if($hasWelFare){
                        $interactUserIds = $hasWelFare['interact_user_ids'] ? explode(',',$hasWelFare['interact_user_ids']) : [];
                        if(!in_array($userid, $interactUserIds)){
                            $interactUserIds[] = $userid;
                            if($hasWelFare['interact'] == sizeof($interactUserIds)){
                                M('welfare')->where(['id'=>$hasWelFare['id']])->save(['state'=>0, 'interact_user_ids'=>implode(',',$interactUserIds)]);
                                M('wallet_frozen')->where(['user_id'=>$touserid])->setDec('value', $hasWelFare['value']);
                                M('wallet_frozen_records')->add(['user_id'=>$touserid, 'value'=>$hasWelFare['value'], 'time'=>time(), 'remark'=>'系统赠送积分(新用户福利) 任务完成', 'type'=>1]);
                                if(isset($config['welfare_score_over_tip']) && $config['welfare_score_over_tip']){
                                    $welfareChat = [
                                        'userid' => $kefu,
                                        'touserid' => $touserid,
                                        'content' => $config['welfare_score_over_tip'],
                                        'data' => '',
                                        'k' => 0,
                                        'single' => 1
                                    ];
                                    $chat = M('privatechat')->add($welfareChat);
                                    if($chat){
                                        D('ChatLists')->updateLists($kefu, $touserid, 1, 0, $welfareChat['content'], 0);
                                        $this->pushNewMsg($welfareChat);
                                    }
                                }
                            }else{
                                M('welfare')->where(['id'=>$hasWelFare['id']])->save(['interact_user_ids'=>implode(',',$interactUserIds)]);
                            }
                        }
                    }
                }
            }

            $this->getOtherList(json_encode(['userid' => $userid_privacy, 'count' => '', 'type' => '']));

            if ($timing) {
                $this->getreadcount(json_encode(['user_id' => $touserid]));
            }

            if($return && $pushNewMsgs[0]){
                if(!isset($intimate)){
                    $intimate = M('user_intimate')->where(['couple_a' => $couple_a])->getField('intimate');
                }
                //此处防止推送的用户亲密度比例不对，重新进行循环计算
                foreach($intimate as $key => $val){
                    if($key=='intimate'){
                        $intimate[$key] = $val / 10;  // 原始亲密度/10
                    }
                }
                $pushNewMsgs[0]['intimate'] = $intimate;
                // if($userid==20378861){
                //     file_put_contents('20378861.log', json_encode($pushNewMsgs[0]), FILE_APPEND);
                // }
                exit(json_encode(['code'=>200,'data'=>$pushNewMsgs[0], 'payer_id'=>$payer_id]));
            }


        }
    }
        public function addTalkold($userid, $touserid, $type=0, $content='', $second=0, $data='', $timing=0, $greet=0, $system_greet=0, $login_greet=0, $single=0, $fate=0, $notice=0, $quality=0, $return = 0, $front_id = '', $is_public = 0)
    {
        $ispayer = I('ispayer', 0);

           
        if ($type != 3) {
            $timenow = time();
            $isWarnWord = 0;

            $pushNewMsgs = [];

            $content = strip_tags($content);
            
            // if ($type ==1){
            //     $content = $content.'?x-oss-process=image/resize,p_50';
            // }
            $is_burn = I('is_burn') ?: 0;
            $config = M('config_system')->where(['category' => ['in', ['kefu', 'chat', 'greet', 'speaker', 'defend', 'welfare', 'two_way_charge']]])->getField('title, content');
            $kefu = intval($config['id']);

            $blacklist = M('blacklist')->where(['user_id' => $touserid, 'to_user' => $userid])->find();
            if ($blacklist) {
                exit(json_encode(['code' => 400, 'msg' => '对方已把你拉黑，可点击TA的头像，进入用户中心，申请解除拉黑']));
            }
            $blacklist = M('blacklist')->where(['to_user' => $touserid, 'user_id' => $userid])->find();
            if ($blacklist) {
                exit(json_encode(['code' => 400, 'msg' => '你已经把对方拉黑，无法发送信息']));
            }

            $userInfo_privacy = $userInfo = M('user')->master(true)->where(['id' => $userid])->find();
            $touserInfo_privacy = $touserInfo = M('user')->master(true)->where(['id' => $touserid])->find();
            if ($userInfo['reg'] && $userInfo['id'] != $kefu && $userInfo['reg'] != $touserInfo['reg']) {
                exit(json_encode(['code' => 400, 'msg' => '用户类型异常']));
            }
            //如果对方被封号也不能发消息
            if ($touserInfo['is_banned']) {
                exit(json_encode(['code' => 400, 'msg' => '对方账号已被冻结']));
            }
            
            //被限制社交 只能和客服聊天 不能和其他用户发消息 能接收 首页也不能被检索到
            $limit_chat = M('limit_chat')->where(['user_id'=>$userid])->find();
            // if ($limit_chat) {
            //     exit(json_encode(['code' => 400, 'msg' => '你已被禁言']));
            // }
            if ($limit_chat) {
                // 允许和客服聊天
                if ($touserid==$kefu) {
                    // 允许的用户关系，继续执行
                } else {
                    exit(json_encode(['code' => 400, 'msg' => '你已被禁言']));
                }
            }
            
           if ($userInfo_privacy['sex'] == '女') {
                if ($userInfo_privacy['realname_auth'] != 2) {
                    exit(json_encode(['code' => 400, 'msg' => '未实名认证']));
                }
                if (strtotime($userInfo_privacy['register_datetime']) >=1749787200 &&  $userInfo_privacy['is_identity_authentication'] != 2) {
                    exit(json_encode(['code' => 400, 'msg' => '未真人认证']));
                }
            }

            $userid_privacy = $userid;
            $touserid_privacy = $touserid;
            $privacyChat = false;
            if ($userInfo['reg'] == 2) {
                $userInfo_privacy = $userInfo;
                $touserInfo_privacy = $touserInfo;
                $userInfo = M('user')->master(true)->where(['id' => $userInfo_privacy['authcode'], 'reg'=>1])->find();
                $touserInfo = M('user')->master(true)->where(['id' => $touserInfo_privacy['authcode'], 'reg'=>1])->find();
                $userid = $userInfo['id'];
                $touserid = $touserInfo['id'];
                $privacyChat = true;
            }
           

            // if ($userInfo['sex'] == '女' && $touserid != $kefu) {
            //     if (!$userInfo['yqr'] && $timenow - strtotime($userInfo['register_datetime']) < 7 * 86400 && $userInfo['realname_auth'] != 2) {
            //         $userConfig = M('config_personal')->where(['user_id' => $userid])->find();
            //         if (!$userConfig || $userConfig['chat_price'] == 0) {
            //             exit(json_encode(['code' => 400, 'msg' => '请先完成实名认证']));
            //         }
            //     }
            // }

            // $chatSingle = M('privatechat_user_single')->where(['user_id'=>$userid])->find();
            // $single = $chatSingle ? 2 : $single;


            $limittime = strtotime('2023-08-01 00:00:00');
            // if (time() >= $limittime) {
            //     if ((strtotime($userInfo['register_datetime']) < $limittime && strtotime($touserInfo['register_datetime']) > $limittime) || (strtotime($userInfo['register_datetime']) > $limittime && strtotime($touserInfo['register_datetime']) < $limittime)) {
            //         exit(json_encode(['code' => 400, 'msg' => '发送失败']));
            //     }
            // }

            if($kefu != $touserid && $kefu != $userid){
                if($type == 0 && ishasPhoneNumber($content)){
                    exit(json_encode(['code' => 400, 'msg' => '禁止发送手机号']));
                }
                if ($userInfo['sex'] == $touserInfo['sex']) {
                    if (strtotime($userInfo['register_datetime']) < $limittime || strtotime($touserInfo['register_datetime']) < $limittime || in_array($touserInfo['entertainment'], [0,2])) {
                        exit(json_encode(['code' => 400, 'msg' => '当前仅支持异性聊天']));
                    // } else {
                    //     $user_attestations = M('user_attestation','','DB_CONFIG9')->where(['user_id'=>['in', [$userid, $touserid]], 'status'=>1])->count();
                    //     if (!$user_attestations) {
                    //         exit(json_encode(['code' => 400, 'msg' => '双方均未经验认证']));
                    //     }
                    }
                }
                // if($content[0] == '[' && substr($content, -1) == ']'){

                // }else{
                //     $sendNum = M('privatechat')->where(['userid'=>$userid, 'content'=>$content])->count();
                //     if($sendNum >= 5){
                //         exit(json_encode(['code' => 400, 'msg' => '禁止重复刷屏']));
                //     }
                // }
            }

            if (!$userInfo || !$touserInfo || $userInfo['delete_time'] || $touserInfo['delete_time']) {
                exit(json_encode(['code' => 400, 'msg' => '账号已注销']));
            }

            //if (($userInfo['is_banned'] || $userInfo_privacy['is_banned']) && $kefu != $touserid) {
            // if ($userInfo['is_banned'] && strtotime($userInfo['banned_end_time']) > $timenow && $kefu != $touserid) {
            if ($userInfo['is_banned']){//被封号也不能私聊客服
                exit(json_encode(['code' => 400, 'msg' => '当前账号已被冻结']));
            }

            // if (!$userInfo['sandbox'] && $touserInfo['sandbox']) {
            //     exit(json_encode(['code' => 400, 'msg' => '无法给对方发送消息']));
            // }

            // $delChat = M('del_chat')->Query("select * from del_chat where (uid=$userid_privacy and to_uid=$touserid_privacy) or (uid=$touserid_privacy and to_uid=$userid_privacy)");
            // if ($delChat) {
            //     $del_ids = [$delChat[0]['id']];
            //     if (isset($delChat[1])) {
            //         $del_ids[] = $delChat[1]['id'];
            //     }
            //     M('del_chat')->where(['id' => ['in', $del_ids]])->delete();
            // }


            if ($kefu != $userid && $kefu != $touserid) {
                //if ($touserInfo['sex'] == '男' && $userInfo['sex'] == '女') {
                $touserConfig = ['chat_price' => 0];
                //} else {
                $touserConfig = M('config_personal')->where(['user_id' => $touserid])->find();

                if (!$touserConfig) {
                    $touserConfig = ['chat_price' => $config['chat_price']];
                } else {
                    $touserConfig = $config['chat_price_switch'] > 0 ? ['chat_price' => $config['chat_price']] : $touserConfig;
                }
                // $datetime = date('Y-m-d H:i:s');
                // $chat_discount = M('act_chat_discount_user')->where("user_id=$touserid and state=0 and starttime <= '$datetime' and endtime >= '$datetime'")->find();
                // if ($chat_discount) {
                //     $touserConfig['chat_price'] = number_format($touserConfig['chat_price'] * $chat_discount['discount'] / 100, 2);
                // }
                // $hasAttestation = M('user_attestation')->where(['user_id'=>$touserid, 'status'=>1])->count();
                //}
            }


            $free = 0;

            $status = 0;  // 好友关系或守护关系
            $money = 0;
            if (!in_array($kefu, [$userid, $touserid]) || !$greet) {
                if (!in_array($type, [9, 10])) {
                    if ($touserConfig['chat_price'] + 0) {
                        /*$attention1 = M('attention')->where(['user_id' => $userid, 'to_user' => $touserid])->find();
                        $attention2 = M('attention')->where(['user_id' => $touserid, 'to_user' => $userid])->find();

                        if (!$attention1 || !$attention2) {*/
                        /*$defend = M('user_defend')->where(['user_id' => $touserid, 'to_user' => $userid, 'angel' => 1])->find();
                        if (!$defend) {*/
                        $status = 1;
                        //}
                        //}
                    }
                }
            }

            $chat_free = 0;
            if ($userid < $touserid) {
                $couple_a = $userid . ',' . $touserid;
            } else {
                $couple_a = $touserid . ',' . $userid;
            }

            /**
             * 双向收费
             */
            // 是否已设置付费方
            $ChargeStatus = 0;
            if ($kefu != $userid && $kefu != $touserid) {
                if(isset($config['two_way_charge_status']) && $config['two_way_charge_status']){
                    $two_way_charge_reg_time = isset($config['two_way_charge_reg_time']) ? strtotime($config['two_way_charge_reg_time']) : 0;
                    $male = $userInfo['sex'] == '女' ? $touserInfo : $userInfo;
                    // 应只对男用户限制双向收费。若注册时间早于开启时间，则默认男用户付费
                    if(strtotime($male['register_datetime']) > $two_way_charge_reg_time){
                        $ChatChargeRecordsMap = $touserid < $userid ? [
                            'user_id' => $touserid,
                            'another_id' => $userid,
                        ] :  [
                            'user_id' => $userid,
                            'another_id' => $touserid,
                        ];
                        $ChatChargeRecords = M('chat_charge_records')->master(true)->where($ChatChargeRecordsMap)->find();
                        if ($ChatChargeRecords) {
                            if($ChatChargeRecords['state']){
                                $ChargeStatus = 1;
                                if ($ChatChargeRecords['payer'] == $userid) {
                                    $recharge_user = $userInfo;
                                } else {
                                    $recharge_user = $touserInfo;
                                    $chat_free = 1;
                                }
                            } else {
                                // 若未设置付费者
                                if ($ChatChargeRecords['payer'] == 0 || $ChatChargeRecords['state'] == 0) {
                                    if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男') {
                                        if ($touserInfo['entertainment'] == 1) {
                                            $ChatChargeRecordsMap['payer'] = $userid;
                                            $ChatChargeRecordsMap['state'] = 1;
                                            $recharge_user = $userInfo;
                                        } else if ($ispayer == 1) {
                                            $ChatChargeRecordsMap['payer'] = $userid;
                                            $ChatChargeRecordsMap['state'] = 1;
                                            $recharge_user = $userInfo;
                                        } else {
                                            $ChatChargeRecordsMap['payer'] = $touserid;
                                            $ChatChargeRecordsMap['state'] = 0;
                                            $recharge_user = $touserInfo;
                                            $chat_free = 1;
                                        }
                                    } else {
                                        $ChatChargeRecordsMap['payer'] = $userid;
                                        $ChatChargeRecordsMap['state'] = 1;
                                        $recharge_user = $userInfo;
                                    }
                                    $ChatChargeRecordsMap['id'] = $ChatChargeRecords['id'];

                                    M('chat_charge_records')->save($ChatChargeRecordsMap);
                                    $ChargeStatus = 1;
                                } elseif ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男') {
                                    // exit(json_encode(['code' => 400, 'msg' => '等待付费方确认']));
                                } else {
                                    // 兼容旧版 回复消息则代表确认
                                    M('chat_charge_records')->where(['id'=>$ChatChargeRecords['id']])->save(['state' => 1]);
                                    $recharge_user = $userInfo;
                                    $ChargeStatus = 1;
                                }
                                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid, json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $touserid_privacy]));
                                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $userid_privacy]));
                            }
                        } else {
                            $ChatChargeRecordsMap['time'] = $timenow;
                            if ($touserInfo['entertainment'] == 1) {
                                $ChatChargeRecordsMap['payer'] = $userid;
                                $ChatChargeRecordsMap['state'] = 1;
                                $recharge_user = $userInfo;
                            // } else if ($userInfo['yqr'] && $userInfo['yqr'] == $touserInfo['yqm']) {
                            //     $ChatChargeRecordsMap['payer'] = $userid;
                            //     $ChatChargeRecordsMap['state'] = 1;
                            //     $recharge_user = $userInfo;
                            // } else if ($userInfo['yqm'] && $userInfo['yqm'] == $touserInfo['yqr']) {
                            //     $ChatChargeRecordsMap['payer'] = $touserid;
                            //     $ChatChargeRecordsMap['state'] = 1;
                            //     $recharge_user = $touserInfo;
                            } else if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男') {
                                if ($ispayer == 1) {
                                    $ChatChargeRecordsMap['payer'] = $userid;
                                    $ChatChargeRecordsMap['state'] = 1;
                                    $recharge_user = $userInfo;
                                } else {
                                    $ChatChargeRecordsMap['payer'] = $touserid;
                                    $ChatChargeRecordsMap['state'] = 0;
                                    $recharge_user = $touserInfo;
                                    $chat_free = 1;
                                }
                            } else {
                                $ChatChargeRecordsMap['payer'] = $userid;
                                $ChatChargeRecordsMap['state'] = 1;
                                $recharge_user = $userInfo;
                            }

                            M('chat_charge_records')->add($ChatChargeRecordsMap);
                            $ChargeStatus = 1;
                        }
                    }
                }
            }

            if (!$notice && $userInfo['sex'] == '女' && $userInfo['id'] != $kefu && $touserInfo['id'] != $kefu && !in_array($userInfo['realname_auth'], [1,2]) && $userInfo['entertainment'] != 1) {
                $userData = M('user_data')->where(['user_id'=>$touserInfo['id']])->find();
                if($userData && $userData['topup'] > 0) {
                    exit(json_encode(['code' => 400, 'msg' => '请先实名']));
                }
            }

            //  其中一方属于系统推送过来的，只有男方是需要付费。否则，谁先发起对话，双方费用需都承担
            if (($userInfo['sex'] == '女' && $touserInfo['sex'] == '男' || $touserInfo['entertainment'] == 1) && $touserInfo['id'] != $kefu) {
                // if($userInfo['realname_auth'] != 2 && strtotime('2023-06-01') > strtotime($userInfo['register_datetime'])){
                //     exit(json_encode(['code' => 400, 'msg' => '未实名认证']));
                // }
                if($userInfo['yqm'] != $touserInfo['yqr'] && ($fate==0 && $timing==0 && $greet==0)){

                    // $selfpush = M('chat_lists')->where(['user_id'=>$userid_privacy, 'another_id'=>$touserid_privacy])->find();
                    // // $selfpull = M('chat_lists')->where(['another_id'=>$userid_privacy, 'user_id'=>$touserid_privacy])->find();
                    //  $selfpull = M('chat_lists')->where(['user_id'=>$touserid_privacy, 'another_id'=>$userid_privacy])->find();
                    $otherlimit = !in_array($type, [20,22]);
                    if ($touserInfo['entertainment'] == 1) {
                        if ($ChargeStatus) {
                            // if ($recharge_user['id'] != $userInfo['id'] || ($recharge_user['id'] == $userInfo['id'] && $touserConfig['chat_price'] == 0)) {
                            //     if(($selfpush && $selfpush['user_first'] == 1) || ($selfpull && $selfpull['another_first'] == 1)){
                            //         // exit(json_encode(['code' => 400, 'msg' => '等待对方回复后才可继续聊天']));
                            //     }
                            // }
                        } else {
                            $recharge_user = $userInfo;
                            $ChargeStatus = 1;
                        }
                    } else {
                        // if($userInfo['realname_auth'] != 2 && $userInfo['yqm'] != $touserInfo['yqr'] && $kefu != $touserid && $kefu != $userid){
                            // $isHasChatWin = M()->Query("(select id from chat_lists where user_id=$touserid and another_id=$userid) union (select id from chat_lists where user_id=$userid and another_id=$touserid)");
                            // if(!$selfpush && !$selfpull && $otherlimit && $kefu != $userid){
                            //     // exit(json_encode(['code' => 400, 'msg' => '未实名认证不能主动向男用户发信息']));
                            //     exit(json_encode(['code' => 401, 'msg' => '不能主动向男用户发信息']));
                            // }
                        // }

                        if($kefu != $touserid && $kefu != $userid && $otherlimit){
                            // if(($selfpush && $selfpush['user_first'] == 1) || ($selfpull && $selfpull['another_first'] == 1)){
                            //     // if ($type == 1) {
                            //     //     if($userInfo['realname_auth'] != 2 && $userInfo['yqm'] != $touserInfo['yqr']){
                            //     //         exit(json_encode(['code' => 400, 'msg' => '未实名认证']));
                            //     //     }
                            //     //     $fate = 1;
                            //     // } else {
                            //         // exit(json_encode(['code' => 400, 'msg' => '等待对方回复后才可继续聊天']));
                            //     // }
                            // }
                            // 亲密度
                            if($type == 0){
                                $intimate = M('user_intimate')->where(['couple_a' => $couple_a])->getField('intimate');
                                if(!$intimate || $intimate <= 0){
                                    if(is_hasNumber($content)){
                                        $cachekeyPSE = 'RSE'.$userid_privacy.'to'.$touserid_privacy;
                                        if (!S($cachekeyPSE)) {
                                            S($cachekeyPSE, 1, 10);
                                            M('privatechat_send_error')->add(['user_id'=>$userid_privacy, 'another_id'=>$touserid_privacy, 'content'=>$content, 'time'=>$timenow, 'reason_type'=>1]);
                                        }
                                        exit(json_encode(['code' => 400, 'msg' => '对方回复后即可发数字']));
                                    }
                                }
                            }
                        }
                    }
                }

                //$greetRecords = M()->Query("select id from greet_records where (user_id=$touserid and to_user=$userid) or (user_id=$userid and to_user=$touserid)");
                // $greetRecords = false;

                // if ($greetRecords) {
                //     $status = 0;
                //     $recharge_user = $touserInfo;
                // } else {
                //     $recharge_user = $userInfo;
                // }
                if (!$ChargeStatus) {
                    $recharge_user = $touserInfo;
                    $chat_free = 1;
                }
            } else {
                if (!$ChargeStatus) {
                    $recharge_user = $userInfo;
                }
            }

            // 我付费，对方免费的情况下，首次发起聊天算打招呼，打招呼有上限
            if ($recharge_user['id'] == $userInfo['id'] && $touserConfig['chat_price'] <= 0 && $userInfo['id'] != $kefu && $touserInfo['id'] != $kefu) {

                $minuid = min($userInfo['id'], $touserInfo['id']);
                $maxuid = max($userInfo['id'], $touserInfo['id']);
                $ischatList = M('chat_lists')->where(['user_id'=>$minuid, 'another_id'=>$maxuid])->find();
                $touserUnReply = ($userInfo['id'] == $minuid && $ischatList['user_first']) || ($userInfo['id'] == $maxuid && $ischatList['another_first']);

                if ($touserUnReply) {
                    // exit(json_encode(['code' => 400, 'msg' => '等待对方回复后才可继续聊天']));
                }
                if (!$ischatList) {
                    $fate = 1;
                    $timing = 1;

                    $sayhiNum = 10;
                    if ($userInfo['noble_grade'] && $userInfo['noble_time'] > time()) {
                        $privilege = M('grade_noble')->where(['grade' => $userInfo['noble_grade']])->getField('privilege');
                        $privilege = explode(',', $privilege);
                        if (in_array(17, $privilege)) {
                            $sayhiNum = 50;
                        }
                    }

                    // $fateuids = M('privatechat')->where(['userid'=>$userInfo['id'], 'is_fate'=>1, 'is_public'=>1, 'money'=>0, 'addtime'=>['egt', date('Y-m-d') . ' 00:00:00']])->getField('touserid', true);
                    // $fateuids = $fateuids ? $fateuids : [];
                    // if (sizeof($fateuids) >= $sayhiNum) {
                    //     exit(json_encode(['code'=>400, 'msg'=>'今日打招呼次数已达上限']));
                    // }
                    $is_public = 1;
                }

            }

            // 服务订单下生成的免费聊天权限
            // $privatechat_free = M('privatechat_free')->where(($userid>$touserid?"user_id=$touserid and another_id=$userid":"user_id=$userid and another_id=$touserid") . " and ((end_time=0 or start_time=0 or end_time>$timenow) or ((server=$userid and confirm in (1,2)) or (server=$touserid and confirm in (1,3))))")->order('id asc')->find();
            // if ($userid == $userid_privacy) {
            //     $privatechat_free = M('privatechat_free')->where(($userid>$touserid?"user_id=$touserid and another_id=$userid":"user_id=$userid and another_id=$touserid") . " and (end_time=0 or start_time=0 or end_time>$timenow)")->order('id asc')->find();
            //     if ($privatechat_free) {
            //         if ($privatechat_free['start_time'] == 0) {
            //         // 说明是线上订单，服务方未发起聊天
            //             if ($privatechat_free['server'] == $userid) {
            //                 // M('privatechat_free')->where(['id'=>$privatechat_free['id']])->save(['start_time'=>$timenow, 'end_time'=>$timenow + $privatechat_free['end_time'] - $privatechat_free['create_time']]);
            //                 M('privatechat_free')->where(['id'=>$privatechat_free['id']])->save(['start_time'=>$timenow, 'end_time'=>9999999999]);
            //                 Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['another_id']]));
            //                 Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['another_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['user_id']]));
            //                 $chat_free = 1;
            //             }
            //         // } else if ($privatechat_free['confirm'] != 0) {
            //         //     if ($privatechat_free['confirm'] == 1) {
            //         //         Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['another_id']]));
            //         //         Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['another_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['user_id']]));
            //         //     } else if ($privatechat_free['server'] == $userid) {
            //         //         Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['another_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['user_id']]));
            //         //     } else {
            //         //         Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['another_id']]));
            //         //     }
            //         } else {
            //             $lianmaiMinute = $privatechat_free['audio_second'] + $privatechat_free['video_second'] > 0 ? ceil(($privatechat_free['audio_second'] + $privatechat_free['video_second']) / 60) : 0;
            //             $free_over = false;
            //             if ($lianmaiMinute == 0) {
            //                 if ($privatechat_free['seller_msg'] >= 200) {
            //                     $free_over = true;
            //                 }
            //             } elseif ($lianmaiMinute <= 10) {
            //                 if ($privatechat_free['seller_msg'] >= 150) {
            //                     $free_over = true;
            //                 }
            //             } elseif ($lianmaiMinute <= 20) {
            //                 if ($privatechat_free['seller_msg'] >= 100) {
            //                     $free_over = true;
            //                 }
            //             } elseif ($lianmaiMinute <= 30) {
            //                 if ($privatechat_free['seller_msg'] >= 50) {
            //                     $free_over = true;
            //                 }
            //             } elseif ($lianmaiMinute < 35) {
            //                 if ($privatechat_free['seller_msg'] >= 0) {
            //                     $free_over = true;
            //                 }
            //             } elseif ($lianmaiMinute >= 35) {
            //                 $free_over = true;
            //             }
            //             if ($free_over) {
            //                 M('privatechat_free')->where(['id'=>$privatechat_free['id']])->save(['end_time'=>time()]);
            //                 Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['user_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['another_id']]));
            //                 Gateway::sendToUid(getenv('SOCKET_PREFIX') . $privatechat_free['another_id'], json_encode(['code' => 200, 'v' => 1, 'action' => 'api/privatechat/detail', 'data' => $privatechat_free['user_id']]));
            //             } else {
            //                 $chat_free = 1;
            //             }
            //         }
            //     }
            // }
            if ($userid < $touserid) {
                $field_count = 'count_a';
                $couple_a = $userid_privacy . ',' . $touserid_privacy;
                $couple_b = $touserid_privacy . ',' . $userid_privacy;
            } else {
                $field_count = 'count_b';
                $couple_a = $touserid_privacy . ',' . $userid_privacy;
                $couple_b = $userid_privacy . ',' . $touserid_privacy;
            }

            $overpayscale = 0;
            // $topcust = 100000;
            // $maxscale = 10;
            $intimate = M('user_intimate')->master(true)->where(['couple_a' => $couple_a])->find();
            // if ($intimate && $intimate['intimate'] >= $topcust) {
            //     $overpayscale = $maxscale;
            // } else {
                // 获取所有关联账号的总支付
                $uids = [];
                $phone = $userInfo['phone'];
                $uids = M('recycle_user')->where(['phone'=>$phone])->getField('user_id', true);
                if ($uids) {
                    $uids[] = $userid;
                    $uids = array_unique($uids);
                    if (sizeof($uids) <= 1) {
                        $uids = [];
                    }
                }
                $device_ids = M('user_repeat_check')->where(['user_id'=>$userid])->getField('device_ids');
                if (($device_ids || $uids) && false) {
                    $device_users = [];
                    $device_userids = [$userid];
                    if ($device_ids) {
                        $device_ids = explode(',', $device_ids);
                        foreach ($device_ids as $device_id) {
                            $devusers = M('user_repeat_check')->where(['_string'=>'FIND_IN_SET('."'$device_id'".',device_ids)'])->cache(true,600)->getField('user_id',true);
                            if ($devusers) {
                                foreach ($devusers as $devuser) {
                                    $device_userids[] = $devuser;
                                    if ($devuser == $touserid) {
                                        continue;
                                    }
                                    if ($devuser > $touserid) {
                                        if (!in_array($touserid . ',' . $devuser, $device_users)) {
                                            $device_users[] = $touserid . ',' . $devuser;
                                        }
                                    } else {
                                        if (!in_array($devuser . ',' . $touserid, $device_users)) {
                                            $device_users[] = $devuser . ',' . $touserid;
                                        }
                                    }
                                }
                            }
                        }
                    }
                    foreach ($uids as $value) {
                        $device_userids[] = $value;
                        if ($value == $touserid) {
                            continue;
                        }
                        if ($value > $touserid) {
                            if (!in_array($touserid . ',' . $value, $device_users)) {
                                $device_users[] = $touserid . ',' . $value;
                            }
                        } else {
                            if (!in_array($value . ',' . $touserid, $device_users)) {
                                $device_users[] = $value . ',' . $touserid;
                            }
                        }
                    }
                    $device_users = array_unique($device_users);
                    $device_userids = array_unique($device_userids);
                    // var_dump($device_userids);exit;
                    // $topupCount = M('user_data')->where(['user_id' => ['in', $device_userids]])->sum('topup');
                    $topupCount = 0;
                    // var_dump($topupCount);exit;
                    if ($topupCount >= 500) {
                        $overpayscale = 60;
                        if ($topupCount >= 15000) {
                            $overpayscale = 30;
                        } elseif ($topupCount >= 10000) {
                            $overpayscale = 50;
                        }
                    } else if (sizeof($device_users)) {
                        $allpays = M('user_intimate')->where(['couple_a' => ['in', $device_users]])->sum('intimate');

                        // exit(json_encode(['code' => 400, 'msg' => $allpays]));
                        // if ($allpays >= $topcust) {
                        //     $overpayscale = $maxscale;
                        // }
                        if ($allpays >= 5000 * 5) {
                            $overpayscale = 30;
                        } else if ($allpays >= 3000 * 5) {
                            $overpayscale = 50;
                        } else if ($allpays >= 1500 * 5) {
                            $overpayscale = 70;
                        }
                    }
                } else {
                    // $topupCount = M('user_data')->where(['user_id' => $userid])->sum('topup');
                    // if ($topupCount >= 500) {
                    //     $overpayscale = 60;
                    //     if ($topupCount >= 15000) {
                    //         $overpayscale = 30;
                    //     } elseif ($topupCount >= 10000) {
                    //         $overpayscale = 50;
                    //     }
                    // }
                }
            // }
            if ($overpayscale) {
                $chat_scale['scale'] = $overpayscale;
            } else {
                // $chat_scale = M('limit_chat_price')->where($userInfo['id']>$touserInfo['id'] ? 'user_id='.$touserInfo['id']. ' and another_id='. $userInfo['id'] : 'user_id='.$userInfo['id']. ' and another_id='. $touserInfo['id'])->find();
                $chat_scale ='';
            }
            // $serviceOrder = M('order_of_service')->where("((user_id=$userid and shopowner=$touserid) or (user_id=$touserid and shopowner=$userid)) and status in (0, 1) and state = 0 and paystate=1 and type=1")->count();
            // if ($serviceOrder) {
            //     $chat_free = 1;
            // }
            // $hasnotdec = in_array($recharge_user['id'], explode(',', $config['chat_over_dec_not']));


            // if ($userInfo['entertainment'] == 1 && $touserInfo['entertainment'] != 1) {
            //     $minuid = min($userInfo['id'], $touserInfo['id']);
            //     $maxuid = max($userInfo['id'], $touserInfo['id']);
            //     $ischatList = M('chat_lists')->where(['user_id'=>$minuid, 'another_id'=>$maxuid])->find();
            //     if (!$ischatList) {
            //         M('user')->where(['id'=>$userInfo['id']])->setField('entertainment', $touserInfo['entertainment']);
            //     }
            // }

            switch ($type) {
                case 0:
                    if ($content == '') exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    if ($userid != $kefu) {
                        // 敏感词检测
                        $contain = M('filter_word')->cache(true, 3600)->where(['state' => 1])->getField('name', true);
                        foreach ($contain as $k => $v) {
                            if (stripos($content, $v) !== false) {
                                exit(json_encode(['code' => 400, 'msg' => '消息含有敏感词"' . $v . '",请重新编辑发送']));
                            }
                        }
                        // $contain = M('ban_word')->cache(true, 3600)->where(['state' => 1])->getField('name', true);
                        $contain = M('ban_word')->where(['state' => 1])->getField('name', true);
                        $maskArr = ['','*','**','***','****','*****'];
                        $sysMask = false;
                        foreach ($contain as $k => $v) {
                            if (stripos($content, $v) !== false) {
                                $content = str_replace($v, $maskArr[mb_strlen($v)]??'*', $content);
                                $sysMask = true;
                            }
                        }
                    }

                    if (!$timing) {

                        $extraMoney = 0;

                        if ($kefu != $userid && $kefu != $touserid) { // 非客服咨询
                            /*if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $touserInfo['is_identity_authentication'] == 2) {
                                $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $userid, 'touserid' => $touserid])->find();
                                if (!$chatRecord) {
                                    $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $touserid, 'touserid' => $userid])->order('id desc')->find();
                                    if ($chatRecord) {
                                        $extraMoney = 1;
                                    }
                                }
                            }*/
                            $check_hour = 1;
                            $check_num = 10;
                            $check_banned = 12;
                            $ten_minutes = 0;
                            // $ten_minutes = M('privatechat')->where([
                            //     'userid'=>$userid_privacy,
                            //     'content'=>$content,
                            //     'addtime'=>['egt', date('Y-m-d H:i:s', strtotime('-'.$check_hour.' minutes'))]
                            // ])->count();
                            if ($ten_minutes >= $check_num - 1) {
                                M('warn_user_chat_records')->add([
                                    'user_id'=>$userid_privacy,
                                    'content'=>$content,
                                    'reason'=>$check_hour.'分钟内发有'.$check_num.'条相同内容',
                                    'time'=>time()
                                ]);
                                if ($userInfo['is_banned'] != 1) {
                                    M('user')->where(['id'=>$userid])->save(['is_banned'=>1,'banned_end_time'=>date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours')), 'banned_desc'=>$check_hour.'分钟内发有'.$check_num.'条相同内容']);
                                    M('config_personal')->where(['user_id'=>$userid])->save(['is_read_rule'=>0]);
                                    $userInfo['is_banned'] = 1;
                                    M('admin_logs')->add([
                                        'channel' => 3,
                                        'toward' => 0,
                                        'money' => 0,
                                        'user_id' => $userid,
                                        'content' => $check_hour.'分钟内发有'.$check_num.'条相同内容,封禁账号至' . date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours'))
                                    ]);
                                }
                            } else {
                                // $ten_minutes = M('privatechat')->master(true)->where([
                                //     'userid'=>$userid_privacy,
                                //     'content'=>$content,
                                //     'addtime'=>['egt', date('Y-m-d H:i:s', strtotime('-1 minutes'))],
                                //     'is_fate'=>0
                                // ])->count();
                                if ($ten_minutes > 18) {
                                    $hasrecords = M('warn_user_chat_records')->master(true)->where([
                                        'user_id'=>$userid_privacy,
                                        'content'=>mb_substr($content, 0, 50),
                                        'time'=>['egt', strtotime(date('Y-m-d'))]
                                    ])->find();
                                    if ($hasrecords) {
                                        M('warn_user_chat_records')->where([
                                            'id'=>$hasrecords['id']
                                        ])->save(['time'=>time()]);
                                    } else {
                                        M('warn_user_chat_records')->add([
                                            'user_id'=>$userid_privacy,
                                            'content'=>$content,
                                            'reason'=>'1分钟内发有20条相同内容',
                                            'time'=>time()
                                        ]);
                                    }
                                }
                            }

                            // if ($userInfo['sex'] == '女') {
                                $arr = preg_split("/([a-zA-Z0-9]+)/", $content, 0, PREG_SPLIT_NO_EMPTY | PREG_SPLIT_DELIM_CAPTURE); 
                                foreach ($arr as $key => $value) {
                                    if (!preg_match("/([a-zA-Z0-9]+)/", $value)) continue;
                                    if ($userInfo['is_banned'] == 1) break;
                                    if (!empty(trim($value)) && mb_strlen($value, 'UTF-8') == strlen($value) && strlen($value) > 1) {
                                        $check_hour = 1;
                                        $check_num = 20;
                                        $check_banned = 12;
                                        $hours1 = M('privatechat')->master(true)->where([
                                            'userid'=>$userid_privacy,
                                            'type'=>0,
                                            'content'=>['like','%'.$value.'%'],
                                            'addtime'=>['egt', date('Y-m-d H:i:s', strtotime('-'.$check_hour.' hours'))]
                                        ])->limit($check_num)->count();

                                        if ($hours1 >= $check_num - 1) {
                                            M('warn_user_chat_records')->add([
                                                'user_id'=>$userid_privacy,
                                                'reason'=>$check_hour.'小时内连发'.$check_num.'次带有相同数字组 封号'.$check_banned.'小时',
                                                'content'=>$value,
                                                'time'=>time()
                                            ]);
                                            if ($userInfo['is_banned'] != 1) {
                                                M('user')->where(['id'=>$userid])->save(['is_banned'=>1,'banned_end_time'=>date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours')), 'banned_desc'=>'系统检测到违规批量发联系方式给平台用户，涉嫌欺骗']);
                                                M('config_personal')->where(['user_id'=>$userid])->save(['is_read_rule'=>0]);
                                                $userInfo['is_banned'] = 1;

                                                M('admin_logs')->add([
                                                    'channel' => 3,
                                                    'toward' => 0,
                                                    'money' => 0,
                                                    'user_id' => $userid,
                                                    'content' => '短时间内发送多条相同字母&数字组,封禁账号至' . date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours'))
                                                ]);


                                                $auto_content = "系统检测到违规批量发联系方式给平台用户，涉嫌欺骗，封禁账号至".date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours'));
                                                // $contain_tip = ['single' => 1, 'userid' => $kefu, 'touserid' => $userid, 'content' => $auto_content, 'finish' => 0, 'type'=>-3, 'data'=>json_encode(['type'=>1, 'content'=>'申请解除封号','state'=>0], JSON_UNESCAPED_UNICODE)];
                                            }
                                        }
                                    }
                                }
                            // }

                        } else {
                            $chat_free = 1;
                        }
                        $is_push = 1;
                        if (!$chat_free) {
                            if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                                $money = $touserConfig['chat_price'];

                                if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                    $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->cache(true, 360)->find();
                                    if ($gradeNoble) {
                                        $privilege = explode(',', $gradeNoble['privilege']);

                                        if (in_array(10, $privilege)) {
                                            $privilegeValue = explode(',', $gradeNoble['value']);

                                            if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                                $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                                $privilegeValue[0] = intval($privilegeValue[0]);

                                                if ($privilegeValue[0] > $userCount) {
                                                    M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                    //$touserConfig['chat_price'] = 0;

                                                    $free = 1;
                                                }
                                            }
                                        }
                                    }
                                }


                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }

                                if (!$free) {
                                    if ($recharge_user['free_chat']) {
                                        /*$chatCount = M('chat_records')->where(['types' => $type, 'user_id' => $userid])->count();

                                        if ($chatCount >= $config['chat_count']) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            M('chat_records')->add(['types' => $type, 'user_id' => $userid, 'to_user' => $touserid, 'create_time' => time()]);

                                            $money = 0;
                                        }*/

                                        M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                        $free = 1;
                                    } else {
                                        // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100) ? 0.1 : 0;
                                        // $extra_recharge_rate = $recharge_user['volley'] > 100 && !$hasnotdec ? 0.1 : 0;
                                        $extra_recharge_rate = 0;
                                        if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                            if ($recharge_user['id'] == $userid) {
                                                exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                            } else {
                                                exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                            }
                                        }
                                    }
                                }
                            }

                            $money = $free ? 0 : $money;
                            if ($chat_scale && $money) {
                                $money = $money * $chat_scale['scale'] / 100;
                                $money = $money < 0.1 ? 0.1 : $money;
                            }
                            if ($recharge_user['id'] == $userid) {
                                // if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                if ($free && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                                } else {
                                    $chat_score = $money;
                                }

                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, 'single' => $single, 'score' => $chat_score * 1];
                                $contain['send_sex'] = $userInfo['sex'];
                            } else {
                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, 'single' => $single, 'score' => 0];
                            }

                            /*if ($recharge_user['id'] == $userid) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }*/

                            /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => ($chat_score + $extraMoney) * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }*/
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'finish' => 1, 'single' => $single];
                            if ($touserid_privacy == $kefu && $single) {
                                $is_push = 0;
                            }
                        }


                        // 添加聊天
                        // $id = M('privatechat')->add($contain);
                        // $contain['id'] = $id;
                        $pushNewMsgs[] = $contain;
                        
                        if ($is_push) {
                        // 更新会话列表
                        D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, $content, 0, $userInfo['sex']);
                        }

                        if (isset($contain_tip) && !empty($contain_tip)) {
                            $pushNewMsgs[] = $contain_tip;
                            // 更新会话列表
                            D('ChatLists')->updateLists($contain_tip['userid'], $contain_tip['touserid'], 1, $contain_tip['type'], $contain_tip['content']);
                        }

                        // 男性 客服自动回复
                        // if ($userInfo['sex'] == '男' && $kefu == $touserid) {
                        //     $auto_customer_service = 0;

                        //     $customer_service_chat = M('customer_service_chat')->where(['user_id' => $userid])->find();
                        //     if ($customer_service_chat) {
                        //         if (($customer_service_chat['create_time'] + 3600) < time()) {
                        //             $auto_customer_service = 1;
                        //             M('customer_service_chat')->where(['id' => $customer_service_chat['id']])->setField('create_time', time());
                        //         }
                        //     } else {
                        //         $auto_customer_service = 1;
                        //         M('customer_service_chat')->add(['user_id' => $userid, 'create_time' => time()]);
                        //     }

                            // if ($auto_customer_service) {
                            //     $auto_content = "由于用户群体比较大，人工客服只能处理身份审核以及突发事件，如需举报，投诉可去用户资料页去投诉用户，如需联系平台，可以去留言。感谢你的支持";
                            //     $contain = ['single' => 1, 'userid' => $touserid, 'touserid' => $userid, 'content' => $auto_content, 'finish' => 1];
                            //     // $id = M('privatechat')->add($contain);

                            //     // $contain['id'] = $id;
                            //     $pushNewMsgs[] = $contain;

                            //     // 更新会话列表
                            //     D('ChatLists')->updateLists($touserid, $userid, 1, 0, $auto_content);
                            // }
                        // }


                        // 提醒词记录
                        if ($kefu != $userid && $kefu != $touserid) {
                            $warnWord = M('chat_tip_word')->where(['is_hidden' => 0, 'sex'=>['in', ['均可', $userInfo['sex']]]])->cache(true, 5)->getField('id, title, single, content');
                            foreach ($warnWord as $k => $v) {
                                if ($v['title']=='*' && $sysMask) continue;
                                if (stripos($content, $v['title']) !== false) {
                                    $contain = ['type' => -1, 'single' => $v['single'], 'userid' => $userid_privacy, 'touserid' => $touserid_privacy, 'content' => $v['content'], 'finish' => 1];
                                    // $id = M('privatechat')->add($contain);

                                    // $contain['id'] = $id;
                                    $pushNewMsgs[] = $contain;

                                    $isWarnWord = 1;

                                    //$this->getNewMsg(json_encode(['userid' => $userid, 'touserid' => $touserid, 'type' => -1]));
                                    break;
                                }
                            }
                        }

                        if ($extraMoney) {
                            $rewardContent = '🎉🎉 恭喜，你的魅力吸引了小哥哥<br>👄 24小时内回复消息还可额外获得金币<br><br>上传更多照片能获得更多搭讪和积分哦~';
                            $contain_1 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => -1, 'single' => 1, "content" => $rewardContent, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                            // $id = M('privatechat')->add($contain_1);

                            // $contain_1['id'] = $id;
                            $pushNewMsgs[] = $contain_1;
                        }
                    } else {
                        $location = I('location');  // 带有跳转链接

                        if ($location) {
                            $datas = I('data');
                            $datas = htmlspecialchars_decode($datas);
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'location' => $location, 'data' => $datas, 'finish' => 1];
                            // $id = M('privatechat')->add($contain);

                            // $contain['id'] = $id;
                            $pushNewMsgs[] = $contain;

                            // 更新会话列表
                            D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, 0, $content);
                        } else {
                            $speed = intval(I('speed'));  // 速配
                            $match = intval(I('match'));  // 夫妻相
                            //$fate = intval(I('fate'));  // 今日缘分

                            if ($speed) {
                                $types = $userInfo['sex'] == '男' ? 2 : 1;

                                $content_default = M('privatechat_default')->where(['types' => $types, 'channel' => 2, 'user_id' => ['in', [0, $touserid]]])->order('rand()')->getField('content');

                                if (!$content_default) {
                                    $content_default = M('privatechat_zhaohu')->where(['types' => $types, 'is_hidden' => 0])->order('rand()')->getField('content');
                                }
                                $speedContent = '❤ 同城速配成功，快把握住缘分吧~';
                                $contain_1 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => 0, 'single' => 1, "content" => $content];
                                $contain_2 = ["userid" => $touserid_privacy, "touserid" => $userid_privacy, "type" => 0, 'single' => 1, "content" => $content_default];
                                $contain_3 = ["userid" => $touserid_privacy, "touserid" => $userid_privacy, "type" => -1, 'single' => 1, "content" => $speedContent, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];

                                // $id = M('privatechat')->add($contain_1);
                                // $contain_1['id'] = $id;
                                $pushNewMsgs[] = $contain_1;
                                // $id = M('privatechat')->add($contain_2);
                                // $contain_2['id'] = $id;
                                $pushNewMsgs[] = $contain_2;
                                //M('privatechat')->add($contain_3);

                                // 更新会话列表
                                D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 1, 0, $content);
                                D('ChatLists')->updateLists($touserid_privacy, $userid_privacy, 1, 0, $content_default);

                            } else if ($match) {
                                $matchContent = '👫 经大数据测算，你和对方具有夫妻相<br>👄 赶快向Ta打个招呼，把握缘分哦~';
                                $contain_1 = ["userid" => $touserid_privacy, "touserid" => $userid_privacy, "type" => -1, 'single' => 1, "content" => $matchContent, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                                $contain_2 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => 0, "content" => $content, 'finish' => 1];

                                //M('privatechat')->add($contain_1);
                                // $id = M('privatechat')->add($contain_2);
                                // $contain_2['id'] = $id;
                                $pushNewMsgs[] = $contain_2;

                                // 更新会话列表
                                D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, 0, $content);
                            } else if ($fate) {
                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "content" => $content, 'finish' => 1, 'is_fate' => 1, "single" => $single, "is_public" => $is_public];

                                $singleFate = 0;
                                if ($userInfo['sex'] == '女' && $userInfo['quality'] == 1) {
                                    // $contain['id'] = M('privatechat')->order('id desc')->getField('id');
                                    $contain['single'] = 2;
                                    $singleFate = 2;
                                }

                                // $id = M('privatechat')->add($contain);
                                // $contain['id'] = $id;
                                $pushNewMsgs[] = $contain;
                                // 更新会话列表
                                D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $singleFate, 0, $content, $single == 2?2:1);
                            } else if ($login_greet) {
                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, 'single' => 1, "content" => $content, 'finish' => 1];

                                // $id = M('privatechat')->add($contain);
                                // $contain['id'] = $id;
                                $pushNewMsgs[] = $contain;
                            } else if ($notice) {
                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, 'single' => $single, "content" => $content, 'finish' => 1];

                                // $id = M('privatechat')->add($contain);
                                // $contain['id'] = $id;
                                $pushNewMsgs[] = $contain;
                                // 更新会话列表
                                D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, $content, $quality ? 2 : 0);
                            } else {
                                if ($userInfo['sex'] == '男') {
                                    $content = '❤ ← 丘比特 → 发现你俩今天很有缘，为你们牵线成功~';
                                    $greetContent = '❤ ← 丘比特 → 牵线成功，给对方发消息可领取红包奖励';
                                    $contain_1 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => 0, 'single' => 1, "content" => $content, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE)];
                                    $contain_2 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => -1, 'single' => 1, "content" => $greetContent, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE), 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                                } else {
                                    $greetContent = '❤ ← 丘比特 → 发现你俩今天很有缘~ <br>👄 赶紧聊聊吧，别错过缘分~';
                                    $contain_1 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => -1, 'single' => 1, "content" => $greetContent, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE), 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];
                                    $contain_2 = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => 0, 'single' => 1, "content" => $content, 'data' => json_encode(['prefix' => '丘比特'], JSON_UNESCAPED_UNICODE), 'finish' => 1];
                                }

                                // $id = M('privatechat')->add($contain_1);
                                // $contain_1['id'] = $id;
                                $pushNewMsgs[] = $contain_1;
                                // $id = M('privatechat')->add($contain_2);
                                // $contain_2['id'] = $id;
                                $pushNewMsgs[] = $contain_2;
                            }
                        }
                    }

                    // if ($userid != $kefu && !$greet && !$notice) {
                        // 日常任务
                        /*$task = M('task')->where(['name' => 'word_chat'])->find();
                        if (($task['reward'] + 0) && ($task['max'] + 0)) {
                            $start = strtotime(date('Ymd'));
                            //$cost = M('volley_desc')->where(['user_id' => $userid, 'content' => '[完成任务] ' . $task['title'], 'time' => ['egt', $start]])->sum('price');

                            $cost = M('task_daily')->where(['user_id' => $userid, 'name' => $task['name'], 'create_time' => ['egt', $start]])->sum('reward');

                            if (($cost + $task['reward']) <= $task['max']) {
                                D('Task')->updateTaskDaily($userid, $task['name'], $task['reward']);

                                M('user_task')->add(['task' => $task['name'], 'user_id' => $userid, 'create_time' => time()]);

                                M('volley_desc')->add(['user_id' => $userid, 'content' => '[完成任务] ' . $task['title'], 'price' => $task['reward'], 'types' => 1, 'time' => time()]);

                                M('user')->where(['id' => $userid])->setInc('volley', $task['reward']);
                            }
                        }*/

                        // 任务
                    //     D('Task')->finish('word_chat', $userid);
                    // }
                    $msg = $content;
                    break;
                case 1:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    if ($kefu == $userid || $kefu == $touserid) {
                        $chat_free = 1;
                    }

                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);
                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                //$touserConfig['chat_price'] = 0;

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }

                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }


                            if (!$free) {
                                if ($recharge_user['free_chat']) {
                                    /*$chatCount = M('chat_records')->where(['types' => $type, 'user_id' => $userid])->count();

                                    if ($chatCount >= $config['chat_count']) {
                                        exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                    } else {
                                        M('chat_records')->add(['types' => $type, 'user_id' => $userid, 'to_user' => $touserid, 'create_time' => time()]);

                                        $money = 0;
                                    }*/

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');
                                } else {
                                    // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                    $extra_recharge_rate = 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                if ($chat_scale && $chat_score) {
                                    $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                    $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, 'single' => $single, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, 'single' => $single, 'score' => 0];
                        }

                        /*if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }*/

                        /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'is_burn' => $is_burn, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'is_burn' => $is_burn, 'money' => $money, 'score' => 0];
                        }*/
                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'is_fate' => $fate, 'is_burn' => $is_burn, 'single' => $single, 'finish' => 1];
                    }

                    // 添加聊天
                    // $id = M('privatechat')->add($contain);

                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    $msg = '[图片]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, $type);
                    if ($userInfo['sex'] == '男' && $kefu != $userid_privacy && $kefu != $touserid_privacy) {
                        $userTopup = M('user_data')->where(['user_id'=>$userInfo['id']])->getField('topup');
                        if (!$userTopup || $userTopup <= 20) {
                            $check_hour = 2;
                            $check_num = 3;
                            $check_banned = 12;
                            $hours1 = M('privatechat')->master(true)->where([
                                'userid'=>$userid_privacy,
                                'type'=>$type,
                                'addtime'=>['egt', date('Y-m-d H:i:s', strtotime('-'.$check_hour.' minutes'))]
                            ])->limit($check_num)->count();

                            if ($hours1 > $check_num - 1) {
                                M('warn_user_chat_records')->add([
                                    'user_id'=>$userid_privacy,
                                    'reason'=>$check_hour.'分钟内连发'.$check_num.'次以上图片 封号'.$check_banned.'小时',
                                    'content'=>'',
                                    'time'=>time()
                                ]);
                                if ($userInfo['is_banned'] != 1) {
                                    M('user')->where(['id'=>$userid])->save(['is_banned'=>1,'banned_end_time'=>date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours')), 'banned_desc'=>'系统检测账号异常']);
                                    M('config_personal')->where(['user_id'=>$userid])->save(['is_read_rule'=>0]);
                                    $userInfo['is_banned'] = 1;

                                    M('admin_logs')->add([
                                        'channel' => 3,
                                        'toward' => 0,
                                        'money' => 0,
                                        'user_id' => $userid,
                                        'content' => '短时间内发送多条图片信息,封禁账号至' . date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours'))
                                    ]);


                                    $auto_content = "系统检测账号异常，封禁账号至".date('Y-m-d H:i:s', strtotime('+'.$check_banned.' hours'));
                                    // $contain_tip = ['single' => 1, 'userid' => $kefu, 'touserid' => $userid, 'content' => $auto_content, 'finish' => 0, 'type'=>-3, 'data'=>json_encode(['type'=>1, 'content'=>'申请解除封号','state'=>0], JSON_UNESCAPED_UNICODE)];
                                }
                            }
                        }
                    }
                    break;
                case 2:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    if ($kefu == $userid || $kefu == $touserid) {
                        $chat_free = 1;
                    }

                    $singleFate = $single;
                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            $response = D('Privatechat')->checkFree($free, $money, $recharge_user, $userid);

                            if ($response['code'] != 200) {
                                exit(json_encode($response));
                            } else {
                                $free = $response['data']['free'];
                            }
                        }

                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }


                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                if ($chat_scale && $chat_score) {
                                    $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                    $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'single' => $single, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'single' => $single, 'score' => 0];
                        }

                        /*if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }*/

                        /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'score' => 0];
                        }*/

                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'single' => $single, "second" => $second, 'finish' => 1];

                        
                        if ($fate && $userInfo['sex'] == '女' && $userInfo['quality'] == 1) {
                            $contain['single'] = 2;
                            // $contain['id'] = M('privatechat')->order('id desc')->getField('id');
                            $singleFate = 2;
                        }
                    }

                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    $msg = '[语音]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $singleFate, $type);

                    if (!$fate && $userInfo['sex'] == '女' && $kefu != $userid_privacy && $kefu != $touserid_privacy) {
                        $check_hour = 5;
                        $check_num = 10;
                        $hours1 = M('privatechat')->master(true)->where([
                            'userid'=>$userid_privacy,
                            'type'=>$type,
                            'addtime'=>['egt', date('Y-m-d H:i:s', strtotime('-'.$check_hour.' minutes'))],
                            'is_fate'=>0,
                            'front_id'=>['NEQ', '']
                        ])->limit($check_num)->count();

                        if ($hours1 > $check_num - 1) {
                            $hasrecords = M('warn_user_chat_records')->master(true)->where([
                                'user_id'=>$userid_privacy,
                                'reason'=>$check_hour.'分钟内连发'.$check_num.'次以上语音',
                                'time'=>['egt', strtotime('-1 hours')]
                            ])->find();
                            if (!$hasrecords) {
                                M('warn_user_chat_records')->add([
                                    'user_id'=>$userid_privacy,
                                    'reason'=>$check_hour.'分钟内连发'.$check_num.'次以上语音',
                                    'content'=>'',
                                    'time'=>time()
                                ]);
                            }
                        }
                    }
                    break;
                case 3:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    if ($kefu != $userid && $kefu != $touserid) { // 非客服咨询
                        // 被动聊天不扣费
                        /*$chatFreeUser = M('chat_free')->where(['user_id' => $userInfo['id'], 'to_user' => $touserInfo['id']])->find();

                        if ($chatFreeUser) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') {
                                $greetRecords = M('greet_records')->where(['user_id' => $userInfo['id'], 'to_user' => $touserInfo['id']])->find();

                                if (!$greetRecords) {
                                    $chat_free = 1;
                                }
                            } else if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男') {
                                $greetRecords = M('greet_records')->where(['user_id' => $touserInfo['id'], 'to_user' => $userInfo['id']])->find();

                                if (!$greetRecords) {
                                    $chat_free = 1;
                                }
                            } else {
                                $chat_free = 1;
                            }
                        } else {
                            $chatFreeToUser = M('chat_free')->where(['user_id' => $touserInfo['id'], 'to_user' => $userInfo['id']])->find();

                            if (!$chatFreeToUser) {
                                $record = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $touserInfo['id'], 'touserid' => $userInfo['id']])->find();

                                if (!$record) {
                                    M('chat_free')->add(['user_id' => $touserInfo['id'], 'to_user' => $userInfo['id'], 'create_time' => time()]);
                                }
                            }
                        }*/
                    } else {
                        $chat_free = 1;
                    }

                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            $response = D('Privatechat')->checkFree($free, $money, $recharge_user, $userid);

                            if ($response['code'] != 200) {
                                exit(json_encode($response));
                            } else {
                                $free = $response['data']['free'];
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, "data" => json_encode(['cover' => I('cover')]), 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, "data" => json_encode(['cover' => I('cover')]), 'score' => 0];
                        }

                        /*if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                        }*/

                        /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                            } else {
                                $chat_score = $money;
                            }
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "data" => json_encode(['cover' => I('cover')]), 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, "data" => json_encode(['cover' => I('cover')]), 'money' => $money, 'score' => 0];
                        }*/
                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, "data" => json_encode(['cover' => I('cover')]), 'finish' => 1];
                    }

                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    $msg = '[视频]';

                    // 更新会话列表
                    //D('ChatLists')->updateLists($userid, $touserid, 0, 3);

                    break;
                case 6:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));
                    if ($kefu == $userid || $kefu == $touserid) {
                        $chat_free = 1;
                    }

                    $singleFate = $single;
                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            $response = D('Privatechat')->checkFree($free, $money, $recharge_user, $userid);

                            if ($response['code'] != 200) {
                                exit(json_encode($response));
                            } else {
                                $free = $response['data']['free'];
                            }
                        }

                        if (!$free && (!$intimate || !$intimate['intimate'])) {
                            $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                            if ($free) {
                                $touserConfig['chat_price'] = 0;
                            }
                        }


                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                if ($chat_scale && $chat_score) {
                                    $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                    $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'single' => $single, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, "second" => $second, 'money' => $money, 'single' => $single, 'score' => 0];
                        }

                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'single' => $single, "second" => $second, 'finish' => 1];

                        
                        if ($fate && $userInfo['sex'] == '女' && $userInfo['quality'] == 1) {
                            $contain['single'] = 2;
                            // $contain['id'] = M('privatechat')->order('id desc')->getField('id');
                            $singleFate = 2;
                        }
                    }


                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    $msg = '[位置]';
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $singleFate, $type);
                    break;
                case 8:
                    $id = I('id');
                    $num = I('num');
                    $num = intval($num);

                    if ($num <= 0) exit(json_encode(['code' => 400, 'msg' => '数量有误']));

                    $gift = M('gift')->find($id);
                    if (!$gift) exit(json_encode(['code' => 400, 'msg' => '礼物类型不存在']));

                    if ($gift['types'] == 2) {
                        if (!$userInfo['noble_grade'] || $userInfo['noble_time'] < time()) {
                            exit(json_encode(['code' => 400, 'msg' => '需先开通VIP']));
                        }

                        $gradeNoble = M()->Query("SELECT * from grade_noble where FIND_IN_SET(6, privilege) order by grade asc limit 1");

                        if (!$gradeNoble) {
                            exit(json_encode(['code' => 400, 'msg' => '无权限']));
                        }

                        if ($userInfo['noble_grade'] < $gradeNoble[0]['grade']) {
                            exit(json_encode(['code' => 400, 'msg' => '需先开通' . $gradeNoble[0]['name'] . 'VIP或以上等级的VIP']));
                        }
                    }

                    if ($touserInfo['is_banned']) {
                    // if ($touserInfo['is_banned'] && strtotime($touserInfo['banned_end_time']) > time()) {
                        exit(json_encode(['code' => 400, 'msg' => '送礼失败']));
                    }

                    $money = $gift['price'] * $num;

                    $time = time();
                    $number = date('YmdHis') . mt_rand(1000, 9999);

                    //$volley = M('user')->where(['id' => $userid])->getField('volley');
                    $volley = $userInfo['volley'];
                    $volley_gift = $userInfo['volley_gift'];
                    $volley_real = $userInfo['volley'] - $userInfo['volley_gift'];
                    $score = $money;
                    if ($userInfo['sex'] == '男') {
                        if ($volley_gift) {
                            $score = $money - ($money>$volley_gift?$volley_gift:$money);
                        }
                        if ($volley < $money) exit(json_encode(['code' => 400, 'msg' => '余额不足']));
                    } else {
                        if ($userInfo['beans'] < $money) exit(json_encode(['code' => 400, 'msg' => '豆豆不足']));
                    }

                    $datetime = date('Y-m-d');
                    // $todaysend = M('privatechat')->where(['type'=>8, 'userid'=>$userid_privacy, 'touserid'=>$touserid_privacy])->where(['addtime'=>['like', $datetime . '%']])->select();
                    // $sendnum = 0;
                    // foreach ($todaysend as $key => $value) {
                    //     $tmp = json_decode($value['data'],true);
                    //     $sendnum += $tmp['money'];
                    // }
                    // if($sendnum + $money > 2000){
                    //     exit(json_encode(['code' => 400, 'msg' => '今日送对方礼物已达上限']));
                    // }
                    // if($sendnum + $num > 2){
                    //     exit(json_encode(['code' => 400, 'msg' => '每日只能送对方两个礼物']));
                    // }

                    $contain = [
                        "userid" => $userid_privacy,
                        "touserid" => $touserid_privacy,
                        "type" => $type,
                        "content" => '[礼物]',
                        'money' => $money,
                        'score' => $score * 1,
                        'is_fate' => $money>0?0:($recharge_user['id'] == $userInfo['id'] && $userInfo['entertainment'] == 1 ? 0 : 1),
                        'finish' => 1,
                        'front_id' => time(),
                        'is_public' => $is_public,
                    ];
                    if ($money) {
                        $gift_json_data = ['money' => $money, 'id' => $id, 'cover' => $gift['cover'], 'num' => $num, 'name' => $gift['name'], 'u_d_id'=>$userInfo_privacy['device_id'], 'payer'=>$userid_privacy,'preview'=>$gift['preview'],'videourl'=>$gift['videourl'],'videojson'=>$gift['videojson']];
                    } else {
                        $gift_json_data = ['money' => $money, 'id' => $id, 'cover' => $gift['cover'], 'num' => $num, 'name' => $gift['name'], 'u_d_id'=>$userInfo_privacy['device_id'],'preview'=>$gift['preview'],'videourl'=>$gift['videourl'],'videojson'=>$gift['videojson']];
                    }
                    $contain['data'] = json_encode($gift_json_data, JSON_UNESCAPED_UNICODE);

                    $singleGift = 0;
                    // 添加聊天
                    if ($timing == 1 && $userInfo['sex'] == '女' && $userInfo['quality'] == 1 && $money <= 0) {
                        // $contain['id'] = M('privatechat')->order('id desc')->getField('id');
                        $contain['single'] = 2;
                        $singleGift = 2;
                    }

                    if ($timing == 1) {
                        $todaySendCount = M('privatechat')->where(["userid" => $userid_privacy,"touserid" => $touserid_privacy,"type" => $type,"content" => '[礼物]','money' => 0, 'addtime'=>['egt', date('Y-m-d') . ' 00:00:00']])->count();
                        if ($todaySendCount >= 2) exit(json_encode(['code' => 400, 'msg' => '今日向对方打招呼已达上限']));
                    }
                    $id = M('privatechat')->add($contain);
                    $contain['id'] = $id;
                    $contain['send_sex'] = $userInfo['sex'];
                    $TencentIMResponse = (new TencentIM)->sendmsg($contain['userid'], $contain['touserid'], $contain['content']??'', $contain, $contain['single']??0);
                    $gift_json_data['MsgKey'] = $TencentIMResponse['MsgKey']??'';
                    $contain['data'] = json_encode($gift_json_data, JSON_UNESCAPED_UNICODE);
                    M('privatechat')->save($contain);

                    $pushNewMsgs[] = $contain;


                    M('gift_record')->add([
                        'num' => $num,
                        'gift_id' => $gift['id'],
                        'user_id' => $userid,
                        'to_user' => $touserid,
                    ]);
                    // 检查用户性别
                    if ($userInfo['sex'] == '女') {
                        $score = 0;
                        D('VolleyDesc')->beans($userid, $money * 1, '给' . $touserInfo_privacy['name'] . '(' . $touserInfo_privacy['id'] . ')赠送礼物：' . $gift['name'] . ' X ' . $num);
                    }else{
                    if ($money > 0) {
                        // 扣除余额
                        D('VolleyDesc')->index($userid, $money * 1, '给' . $touserInfo_privacy['name'] . '(' . $touserInfo_privacy['id'] . ')赠送礼物：' . $gift['name'] . ' X ' . $num);

                        // 创建订单
                        M('order_common')->add([
                            'number' => $number,
                            'user_id' => $userid,
                            'money' => $money,
                            'status' => 1,
                            'types' => 4,
                            'data' => json_encode(['id' => $id, 'touserid' => $touserid, 'num' => $num]),
                            'create_time' => $time,
                            'update_time' => $time,
                        ]);

                        if ($intimate) {
                            M('user_intimate')->where(['id' => $intimate['id']])->save([
                                $field_count => $intimate[$field_count] + $money,
                                'intimate' => $intimate['intimate'] + $money * 1,
                                'update_time' => time(),
                                'unshow'=>$money>0?0:$intimate['unshow']
                            ]);
                        } else {
                            M('user_intimate')->add([
                                'couple_a' => $couple_a,
                                'couple_b' => $couple_b,
                                $field_count => $money,
                                'intimate' => $money * 1,
                                'create_time' => time(),
                                'update_time' => time()
                            ]);
                        }

                        M('user')->where(['id' => $touserid])->setInc('charm_value', $money * 1);

                        // 榜单记录
                        /*$records_types = $touserInfo['sex'] == '女' ? '1,2,3,6' : '1,3,4,6';
                        D('RankingRecords')->index($records_types, $userid, $touserid, $money);*/



                        $giftsum = M('order_common')->master(true)->where(['user_id' => $userid, 'data'=>['like', '%"touserid":"'.$touserid.'","num"%'], 'status'=>1])->sum('money');
                        // if($giftsum >= 2000){
                        //     $tipContent = '平台不存在送礼物解锁联系方式以及解锁免费聊天权限的功能，请你知悉。';
                        //     $tipcontain = ["userid" => $touserid_privacy, "touserid" => $userid_privacy, "type" => -1, 'single' => 1, "content" => $tipContent, 'isRead' => 1, 'finish' => 1];
                        //     $pushNewMsgs[] = $tipcontain;
                        // }

                    }
                    if ($score) {
                        // 分成
                        $fencheng_content = '收获' . $userInfo_privacy['name'] . '(' . $userInfo_privacy['id'] . ')赠送的礼物：' . $gift['name'] . 'X' . $num;

                        D('User')->fencheng($touserid, $userid, $score * 1, 'gift', $fencheng_content);
                    }
                    }
                    $msg = '[礼物]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $singleGift, 8);

                    break;
                case 11:
                    if (!$content) exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                    $content = intval($content);

                    $where = [
                        'id' => $content,
                        'is_hidden' => 0,
                    ];
                    $sticker = M('chat_sticker')->field('image')->where($where)->find();
                    if (!$sticker) {
                        exit(json_encode(['code' => 400, 'msg' => '表情不存在或已下线']));
                    } else {
                        $content = $sticker['image'];
                    }


                    $extraMoney = 0;

                    if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                    } else {
                        $chat_free = 1;
                    }

                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);

                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                //$touserConfig['chat_price'] = 0;

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }

                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }


                            if (!$free) {
                                if ($recharge_user['free_chat']) {

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                    $free = 1;
                                } else {
                                    // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                    $extra_recharge_rate = 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "data" => $data, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "data" => $data, "content" => $content, 'money' => $money, 'score' => 0];
                        }

                    } else {
                        if ($userInfo['sex'] == '女' && $userInfo['quality'] == 1) {
                            $single = 2;
                        }
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "data" => $data, "content" => $content, 'is_fate' => $fate, "single" => $single, 'finish' => 1];
                    }
                    
                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;
                    
                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 11, $content, 0, $userInfo['sex']);

                    // if ($userid != $kefu && !$greet && !$notice) {
                        // 任务
                    //     D('Task')->finish('word_chat', $userid);
                    // }
                    $msg = '[表情]';
                    break;
                case 12:
                    if ($content == '') exit(json_encode(['code' => 400, 'msg' => '内容不能为空']));

                        // 敏感词检测
                        $contain = M('filter_word')->cache(true)->where(['state' => 1])->getField('name', true);
                        foreach ($contain as $k => $v) {
                            if (stripos($content, $v) !== false) {
                                exit(json_encode(['code' => 400, 'msg' => '消息含有敏感词"' . $v . '",请重新编辑发送']));
                            }
                        }

                        $extraMoney = 0;

                        if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                            /*if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $touserInfo['is_identity_authentication'] == 2) {
                                $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $userid, 'touserid' => $touserid])->find();
                                if (!$chatRecord) {
                                    $chatRecord = M('privatechat')->where(['type' => ['egt', 0], 'single' => 0, 'userid' => $touserid, 'touserid' => $userid])->order('id desc')->find();
                                    if ($chatRecord) {
                                        $extraMoney = 1;
                                    }
                                }
                            }*/
                        } else {
                            $chat_free = 1;
                        }

                        if (!$chat_free) {
                            if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                                $money = $touserConfig['chat_price'];

                                if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                    $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                    if ($gradeNoble) {
                                        $privilege = explode(',', $gradeNoble['privilege']);

                                        if (in_array(10, $privilege)) {
                                            $privilegeValue = explode(',', $gradeNoble['value']);

                                            if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                                $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                                $privilegeValue[0] = intval($privilegeValue[0]);

                                                if ($privilegeValue[0] > $userCount) {
                                                    M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                    //$touserConfig['chat_price'] = 0;

                                                    $free = 1;
                                                }
                                            }
                                        }
                                    }
                                }

                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }


                                if (!$free) {
                                    if ($recharge_user['free_chat']) {
                                        /*$chatCount = M('chat_records')->where(['types' => $type, 'user_id' => $userid])->count();

                                        if ($chatCount >= $config['chat_count']) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            M('chat_records')->add(['types' => $type, 'user_id' => $userid, 'to_user' => $touserid, 'create_time' => time()]);

                                            $money = 0;
                                        }*/

                                        M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                        $free = 1;
                                    } else {
                                        // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                        $extra_recharge_rate = 0;
                                        if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                            if ($recharge_user['id'] == $userid) {
                                                exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                            } else {
                                                exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                            }
                                        }
                                    }
                                }
                            }

                            $money = $free ? 0 : $money;
                            if ($chat_scale && $money) {
                                $money = $money * $chat_scale['scale'] / 100;
                                $money = $money < 0.1 ? 0.1 : $money;
                            }

                            if ($recharge_user['id'] == $userid) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                                } else {
                                    $chat_score = $money;
                                }

                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                            } else {
                                $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }

                            /*if ($recharge_user['id'] == $userid) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => $chat_score * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }*/

                            /*if ($recharge_user['id'] == $userid && (($userInfo['sex'] == '男' && $touserInfo['sex'] == '女') || ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男'))) {
                                if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && !$money) {
                                    $chat_score = $touserConfig['chat_price'];
                                } else {
                                    $chat_score = $money;
                                }
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => ($chat_score + $extraMoney) * 1];
                            } else {
                                $contain = ["userid" => $userid, "touserid" => $touserid, "type" => $type, "content" => $content, 'money' => $money, 'score' => 0];
                            }*/
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $content, 'finish' => 1, 'single' => $single];
                        }

                        if($data){
                            $contain['data'] = $data;
                        }else{
                            exit(json_encode(['code' => 400, 'msg' => '操作错误']));
                        }
                        
                        // 添加聊天
                        // $id = M('privatechat')->add($contain);
                        // $contain['id'] = $id;
                        $pushNewMsgs[] = $contain;
                        
                        // 更新会话列表
                        D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, $content, 0, $userInfo['sex']);


                        // 男性 客服自动回复
                        if ($userInfo['sex'] == '男' && $kefu == $touserid) {
                            $auto_customer_service = 0;

                            $customer_service_chat = M('customer_service_chat')->where(['user_id' => $userid])->find();
                            if ($customer_service_chat) {
                                if (($customer_service_chat['create_time'] + 3600) < time()) {
                                    $auto_customer_service = 1;
                                    M('customer_service_chat')->where(['id' => $customer_service_chat['id']])->setField('create_time', time());
                                }
                            } else {
                                $auto_customer_service = 1;
                                M('customer_service_chat')->add(['user_id' => $userid, 'create_time' => time()]);
                            }

                            // if ($auto_customer_service) {
                            //     $auto_content = "由于用户群体比较大，人工客服只能处理身份审核以及突发事件，如需举报，投诉可去用户资料页去投诉用户，如需联系平台，可以去留言。感谢你的支持";
                            //     $contain = ['single' => 1, 'userid' => $touserid, 'touserid' => $userid, 'content' => $auto_content, 'finish' => 1];
                            //     // $id = M('privatechat')->add($contain);
                            //     // $contain['id'] = $id;
                            //     $pushNewMsgs[] = $contain;

                            //     // 更新会话列表
                            //     D('ChatLists')->updateLists($touserid, $userid, 1, 0, $auto_content);
                            // }
                        }


                        // 提醒词记录
                        if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '男' && $kefu != $userid && $kefu != $touserid) {
                            $warnWord = M('chat_tip_word')->where(['is_hidden' => 0, 'sex'=>['in', ['均可', $userInfo['sex']]]])->cache(true, 5)->getField('id, title, single, content');
                            foreach ($warnWord as $k => $v) {
                                if ($v['title']=='*' && $sysMask) continue;
                                if (stripos($content, $v['title']) !== false) {
                                    $contain = ['type' => -1, 'single' => $v['single'], 'userid' => $userid_privacy, 'touserid' => $touserid_privacy, 'content' => $v['content'], 'finish' => 1];
                                    // $id = M('privatechat')->add($contain);
                                    // $contain['id'] = $id;
                                    $pushNewMsgs[] = $contain;

                                    $isWarnWord = 1;

                                    //$this->getNewMsg(json_encode(['userid' => $userid, 'touserid' => $touserid, 'type' => -1]));
                                    break;
                                }
                            }
                        }


                    // if ($userid != $kefu && !$greet && !$notice) {
                    //     // 任务
                    //     D('Task')->finish('word_chat', $userid);
                    // }
                    $msg = $content;
                    break;
                case 13:
                    $extraMoney = 0;

                    if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                    } else {
                        $chat_free = 1;
                    }

                    $hflen = 0;
                    $hfnum = 0;
                    while(!$hflen){
                        if(S('heartfeltsLimit:' . $userid_privacy)){
                            exit(json_encode(['code'=>201, 'msg'=>'发送过于频繁，请稍后再试']));
                        }
                        $hfnum++;
                        if($hfnum>3){
                            exit(json_encode(['code'=>201, 'msg'=>'请稍后再试']));
                        }
                        $heartfeltsCache = S('heartfelts:' . $userid_privacy);
                        $heartfeltsWhere = [];
                        if($heartfeltsCache){
                            $heartfeltsCache = explode(',', $heartfeltsCache);
                            $heartfeltsWhere['id'] = ['not in', $heartfeltsCache];
                        }else{
                            $heartfeltsCache = [];
                        }
                        $heartfelts = M('chat_heartfelt')->where($heartfeltsWhere)->select();
                        $hflen = sizeof($heartfelts);
                        if(!$hflen){
                            S('heartfeltsLimit:' . $userid_privacy, time(), 60);
                            S('heartfelts:' . $userid_privacy, null);
                        }else{
                            $hfitem = $heartfelts[rand(0, $hflen - 1)];
                            array_push($heartfeltsCache, $hfitem['id']);
                            S('heartfelts:' . $userid_privacy, implode(',', $heartfeltsCache), 120);
                        }
                    }


                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);

                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }


                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }

                            if (!$free) {
                                if ($recharge_user['free_chat']) {

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                    $free = 1;
                                } else {
                                    // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                    $extra_recharge_rate = 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $hfitem['title'], 'data' => $hfitem['content'], 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $hfitem['title'], 'data' => $hfitem['content'], 'money' => $money, 'score' => 0];
                        }

                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => $hfitem['title'], 'data' => $hfitem['content'], 'finish' => 1, 'single' => $single];
                    }
                    
                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;
                    
                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, $hfitem['title'], 0, $userInfo['sex']);


                    $msg = $hfitem['title'];
                    break;
                case 14:
                    $extraMoney = 0;
                    if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                    } else {
                        $chat_free = 1;
                    }

                    $chat = M('privatechat')->master(true)->where(['id'=>$content])->find();
                    if($chat['state'] == 3){
                        exit(json_encode(['code'=>201, 'msg'=>'已经回答过该问题']));
                    }
                    if($chat['userid'] == $userid_privacy){
                        if($chat['state'] == 1){
                            exit(json_encode(['code'=>201, 'msg'=>'已经回答过该问题']));
                        }
                    }elseif($chat['state'] == 2){
                        exit(json_encode(['code'=>201, 'msg'=>'已经回答过该问题']));
                    }

                    $state = $chat['state'] ? 3 : ($chat['userid'] == $userid_privacy ? 1 : 2);
                    $answer = json_decode($chat['data'], true);
                    if($answer && isset($answer[$data])){
                        $answer = $answer[$data];
                    }else{
                        exit(json_encode(['code'=>201, 'msg'=>'操作错误']));
                    }

                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);

                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }


                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }

                            if (!$free) {
                                if ($recharge_user['free_chat']) {

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                    $free = 1;
                                } else {
                                    // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                    $extra_recharge_rate = 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '问:'.$chat['content'].'<br />答:'.$answer, 'order_id' => $chat['id'], 'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '问:'.$chat['content'].'<br />答:'.$answer, 'order_id' => $chat['id'], 'money' => $money, 'score' => 0];
                        }

                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '问:'.$chat['content'].'<br />答:'.$answer, 'order_id' => $chat['id'], 'finish' => 1, 'single' => $single];
                    }
                    
                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    M('privatechat')->where(['id'=>$chat['id']])->setField('state', $state);
                    
                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, '问:'.$chat['content'].'<br />答:'.$answer, 0, $userInfo['sex']);


                    $msg = '问:'.$chat['content'].'<br />答:'.$answer;
                    break;
                case 15:
                    $extraMoney = 0;
                    if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                    } else {
                        $chat_free = 1;
                    }
                    $ChatScriptBox = [];
                    $num = 0;
                    while(sizeof($ChatScriptBox) < 6){
                        $csbWhere = sizeof($ChatScriptBox) ? ['id'=>['not in', array_column($ChatScriptBox, 'id')]] : [];
                        $csb = M('chat_script_box')->where('rand()')->where($csbWhere)->limit(6 - sizeof($ChatScriptBox))->select();
                        $ChatScriptBox = array_merge($ChatScriptBox, $csb);
                        $num++;
                        if($num>10){
                            exit(json_encode(['code'=>201, 'msg'=>'服务器繁忙，请稍后再试']));
                        }
                    }
                    $ChatScriptBox = array_column($ChatScriptBox, 'content');
                    $ChatScriptBox = json_encode($ChatScriptBox, JSON_UNESCAPED_UNICODE);

                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);

                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }


                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }

                            if (!$free) {
                                if ($recharge_user['free_chat']) {

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                    $free = 1;
                                } else {
                                    // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                    $extra_recharge_rate = 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '快和我一起来摇骰子吧', 'data'=>$ChatScriptBox,  'money' => $money, 'score' => $chat_score * 1];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '快和我一起来摇骰子吧', 'data'=>$ChatScriptBox,  'money' => $money, 'score' => 0];
                        }

                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '快和我一起来摇骰子吧', 'data'=>$ChatScriptBox,  'finish' => 1, 'single' => $single];
                    }
                    
                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    M('privatechat')->where(['id'=>$chat['id']])->setField('state', $state);
                    
                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, '快和我一起来摇骰子吧', 0, $userInfo['sex']);


                    $msg = '快和我一起来摇骰子吧';
                    break;
                case 16:
                    $extraMoney = 0;
                    if (!$chat_free && $kefu != $userid && $kefu != $touserid) { // 非客服咨询
                    } else {
                        $chat_free = 1;
                    }


                    $chat = M('privatechat')->master(true)->where(['id'=>$content, 'touserid'=>$userid_privacy, 'state'=>0])->find();
                    if(!$chat){
                        exit;
                    }

                    $answer = json_decode($chat['data'], true);

                    $pubrand = rand(1,6);
                    $subrand = rand(1,6);
                    $randsum = $pubrand + $subrand;
                    switch($randsum){
                        case 2:
                        case 12:
                            $answerIdx = 0;
                            break;
                        case 3:
                        case 11:
                            $answerIdx = 1;
                            break;
                        case 4:
                        case 10:
                            $answerIdx = 2;
                            break;
                        case 5:
                        case 9:
                            $answerIdx = 3;
                            break;
                        case 6:
                        case 8:
                            $answerIdx = 4;
                            break;
                        default:
                            $answerIdx = 5;
                    }


                    $pushNewMsgs[] = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => 17, "content" => $subrand, 'finish' => 1, 'score' => 0];
                    $pushNewMsgs[] = ["userid" => $touserid_privacy, "touserid" => $userid_privacy, "type" => 17, "content" => $pubrand, 'finish' => 1, 'score' => 0];

                    if (!$chat_free) {
                        if ($status) {
                                // $touserConfig['chat_price'] = $hasAttestation == 0 && $touserConfig['chat_price'] >= 2 ? 2 : $touserConfig['chat_price'];
                            $money = $touserConfig['chat_price'];

                            if ($recharge_user['noble_time'] > time() && $recharge_user['noble_grade']) {
                                $gradeNoble = M('grade_noble')->where(['grade' => $recharge_user['noble_grade']])->find();

                                if ($gradeNoble) {
                                    $privilege = explode(',', $gradeNoble['privilege']);

                                    if (in_array(10, $privilege)) {
                                        $privilegeValue = explode(',', $gradeNoble['value']);

                                        if (isset($privilegeValue[0]) && $privilegeValue[0]) {
                                            $userCount = M('grade_noble_use')->where(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => ['egt', strtotime(date('Ymd'))]])->count();

                                            $privilegeValue[0] = intval($privilegeValue[0]);

                                            if ($privilegeValue[0] > $userCount) {
                                                M('grade_noble_use')->add(['types' => 1, 'user_id' => $recharge_user['id'], 'create_time' => time()]);

                                                $free = 1;
                                            }
                                        }
                                    }
                                }
                            }

                                if (!$free && (!$intimate || !$intimate['intimate'])) {
                                    $free = $this->dayFreeChat($userid_privacy, $touserid_privacy);
                                    if ($free) {
                                        $touserConfig['chat_price'] = 0;
                                    }
                                }


                            if (!$free) {
                                if ($recharge_user['free_chat']) {

                                    M('user')->where(['id' => $recharge_user['id']])->setDec('free_chat');

                                    $free = 1;
                                } else {
                                    // $extra_recharge_rate = ($recharge_user['sex'] == '男' && $recharge_user['volley'] > 100 && !$hasnotdec) ? 0.1 : 0;
                                    $extra_recharge_rate = 0;
                                    if ($recharge_user['volley'] < $money * (1 + $extra_recharge_rate)) {
                                        if ($recharge_user['id'] == $userid) {
                                            exit(json_encode(['code' => 300, 'msg' => '余额不足，无法发送消息']));
                                        } else {
                                            exit(json_encode(['code' => 400, 'msg' => '对方余额不足，无法发送消息']));
                                        }
                                    }
                                }
                            }
                        }

                        $money = $free ? 0 : $money;
                        if ($chat_scale && $money) {
                            $money = $money * $chat_scale['scale'] / 100;
                            $money = $money < 0.1 ? 0.1 : $money;
                        }

                        if ($recharge_user['id'] == $userid) {
                            if ($userInfo['sex'] == '男' && $touserInfo['sex'] == '女' && $free && !$money) {
                                $chat_score = $touserConfig['chat_price'];
                                    if ($chat_scale && $chat_score) {
                                        $chat_score = $chat_score * $chat_scale['scale'] / 100;
                                        $chat_score = $chat_score < 0.1 ? 0.1 : $chat_score;
                                    }
                            } else {
                                $chat_score = $money;
                            }

                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '点数之和是' . $randsum . '，请' . $answer[$answerIdx], 'money' => $money, 'score' => $chat_score * 1, 'order_id' => $content];
                        } else {
                            $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '点数之和是' . $randsum . '，请' . $answer[$answerIdx], 'money' => $money, 'score' => 0, 'order_id' => $content];
                        }

                    } else {
                        $contain = ["userid" => $userid_privacy, "touserid" => $touserid_privacy, "type" => $type, "content" => '点数之和是' . $randsum . '，请' . $answer[$answerIdx], 'finish' => 1, 'single' => $single, 'order_id' => $content];
                    }
                    
                    // 添加聊天
                    // $id = M('privatechat')->add($contain);
                    // $contain['id'] = $id;
                    $pushNewMsgs[] = $contain;

                    M('privatechat')->where(['id'=>$chat['id']])->setField('state', 1);
                    
                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, $single, 0, '点数之和是' . $randsum . '，请' . $answer[$answerIdx], 0, $userInfo['sex']);


                    $msg = '点数之和是' . $randsum . '，请' . $answer[$answerIdx];
                    break;

                case 18:
                    $contain = [
                        "userid" => $userid_privacy,
                        "touserid" => $touserid_privacy,
                        "type" => $type,
                        "content" => '[礼物]',
                        'finish' => 1,
                        "data" => $data,
                        'front_id' => time(),
                    ];

                    $pushNewMsgs[] = $contain;

                    $msg = '[礼物]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, $type, $contain['content']);

                    break;
                case 19:
                    $contain = [
                        "userid" => $userid_privacy,
                        "touserid" => $touserid_privacy,
                        "type" => $type,
                        "content" => '[商品代付]请你帮我付个款吧',
                        'finish' => 1,
                        "data" => $data,
                        'front_id' => time(),
                    ];

                    $pushNewMsgs[] = $contain;

                    $msg = '[礼物]';

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, $type, $contain['content']);

                    break;
                case 20:
                    $contain = [
                        "userid" => $userid_privacy,
                        "touserid" => $touserid_privacy,
                        "type" => $type,
                        "content" => '[征婚]'.$content,
                        'finish' => 1,
                        "data" => $data,
                        'front_id' => time(),
                    ];

                    $pushNewMsgs[] = $contain;

                    $msg = '[征婚]'.$content;

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, $type, $contain['content']);

                    break;
                case 21:
                    $contain = [
                        "userid" => $userid_privacy,
                        "touserid" => $touserid_privacy,
                        "type" => $type,
                        "content" => $content,
                        'finish' => 1,
                        "data" => $data,
                        'front_id' => $front_id?:time(),
                    ];

                    $pushNewMsgs[] = $contain;

                    $msg = $content;

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, $type, $contain['content']);

                    break;
                case 22:
                    $contain = [
                        "userid" => $userid_privacy,
                        "touserid" => $touserid_privacy,
                        "type" => $type,
                        "content" => $content,
                        'single' => $single,
                        'finish' => 1,
                        "data" => $data,
                        'front_id' => time(),
                    ];

                    $pushNewMsgs[] = $contain;

                    $msg = '[盲盒消息]'.$content;

                    // 更新会话列表
                    D('ChatLists')->updateLists($userid_privacy, $touserid_privacy, 0, $type, $contain['content'], 3);

                    break;
                default:
                    exit(json_encode(['code' => 400, 'msg' => '操作错误']));
            }
            M()->startTrans();
            if (!$system_greet) {
                if (!in_array($kefu, [$userid, $touserid]) || !$greet) {
                    if (!in_array($type, [8, 9, 10])) {
                        if (!$free && ($money + 0)) {
                            if ($recharge_user['id'] == $userid || !$chat_free) {
                                $recharge_msg = $recharge_user['id'] == $userid ? '给' . $touserInfo_privacy['name'] . '(' . $touserInfo_privacy['id'] . ')发消息扣金币' : $userInfo_privacy['name'] . '(' . $userInfo_privacy['id'] . ')发消息扣金币';
                                // 扣除余额
                                $IncOk = D('VolleyDesc')->index($recharge_user['id'], $money, $recharge_msg);
                            }else{
                                $IncOk = true;
                            }
                        }else{
                            $IncOk = true;
                        }
                    }else{
                        $IncOk = true;
                    }

                    if($recharge_user['id'] != $userid){


                        $scoreChat = M('privatechat')->master(true)->where(['userid' => $touserid_privacy, 'touserid' => $userid_privacy, 'score' => ['gt', 0], 'finish' => 0])->select();

                        $ids = array_column($scoreChat, 'id');
                        if (sizeof($ids)) {
                            
                            foreach ($ids as $val){
                                M('privatechat')->where(['id' => $val])->save(['finish' => 1]);
                            }
                            // M('privatechat')->where(['id' => ['in', $ids]])->save(['finish' => 1]);
                            // $chats = M('privatechat')->where(['id' => ['in', $ids]])->select();
                            // foreach ($chats as $key => $value) {
                            //     $MsgKey = json_decode($value['data'], true)['MsgKey'];
                            //     (new TencentIM)->modify_c2c_msg($userid_privacy, $touserid_privacy, $MsgKey, json_encode($value, true));
                            // }
                        }
                        $scoreData = [];
                        $scoreUpdate = 0;

                        $content = '回复' . $touserInfo_privacy['name'] . '(' . $touserInfo_privacy['id'] . ')的消息获得积分';

                        foreach ($scoreChat as $item) {
                            if (!in_array($item['type'], [8, 9, 10])) {
                                $money = $item['score'];
                            } else {
                                $money = 0;
                            }

                            $scoreData[] = [
                                'uid' => $userid,
                                'touid' => $touserid,
                                'content' => $content,
                                'money' => $money,
                                'type' => 1,
                                'time' => time(),
                            ];

                            $scoreUpdate += $money;
                        }

                        if ($scoreUpdate) {

                            // if ($userInfo['sex'] == '女' && $touserInfo['sex'] == '女') {

                            // } else {
                                // 榜单记录
                                //D('RankingRecords')->index(1, $userid, $touserid, $scoreUpdate * 10);

                                foreach ($scoreData as $value) {
                                    if($value['money']){
                                        // 分成
                                        D('User')->fencheng($userid, $touserid, $value['money'], 'chat', $content);
                                    }
                                }

                                //M('yaoqing_records')->addAll($scoreData);
                                //M('user')->where(['id' => $userid])->setInc('score', $scoreUpdate);
                                M('user')->where(['id' => $userid_privacy])->setInc('charm_value', $scoreUpdate);
                            // }


                            // 亲密度
                            if ($intimate) {
                                M('user_intimate')->where(['id' => $intimate['id']])->save([
                                    $field_count => $intimate[$field_count] + $scoreUpdate * 10,
                                    'intimate' => $intimate['intimate'] + $scoreUpdate,
                                    'update_time' => time(),
                                    'unshow'=>$scoreUpdate>0?0:$intimate['unshow']
                                ]);
                            } else {
                                M('user_intimate')->add([
                                    'couple_a' => $couple_a,
                                    'couple_b' => $couple_b,
                                    $field_count => $scoreUpdate * 10,
                                    'intimate' => $scoreUpdate,
                                    'create_time' => time(),
                                    'update_time' => time()
                                ]);
                            }
                            /*$intimate = M('user_intimate')->where(['couple_a' => $couple_a])->find();

                            $result = M('user_defend')->where(['user_id' => $touserid, 'to_user' => $userid])->find();

                            if (!$userInfo['angel']) {

                                $types = $userInfo['sex'] == '女' ? 2 : 1;
                                $gradeCharm = M('grade_charm')->where(['types' => $types, 'min' => ['elt', $userInfo['charm_value']]])->order('grade desc')->getField('grade');

                                //$gift_money = $userInfo['sex'] == '女' ? $gradeCharm * 100 : $gradeCharm * 20;

                                if ($userInfo['sex'] == '女') {
                                    $gift_money = $gradeCharm * $config['female_times'];
                                    if ($gift_money < $config['female_min']) {
                                        $gift_money = $config['female_min'];
                                    }
                                } else {
                                    $gift_money = $gradeCharm * $config['male_times'];
                                    if ($gift_money < $config['male_min']) {
                                        $gift_money = $config['male_min'];
                                    }
                                }

                                $hadMoney = $userid > $touserid ? $intimate['count_a'] : $intimate['count_b'];

                                $mustMoney = $gift_money - ($hadMoney - $money);

                                $isAngel = 0;
                                if ($mustMoney <= $money) {
                                    $isAngel = 1;
                                } else {
                                    $gradeDefend = M('grade_defend')->where(['min' => ['elt', $hadMoney]])->order('grade desc')->find();

                                    if ($gradeDefend) {
                                        $isAngel = 1;
                                    }
                                }

                                if ($isAngel) {
                                    M('user')->where(['id' => $userid])->setField('angel', $touserid);
                                    M('user_defend')->where(['user_id' => ['neq', $touserid], 'to_user' => $userid])->save(['angel' => 0, 'update_time' => $update_time]);

                                    $isAngel = 1;
                                    $update_time = time();
                                } else {
                                    $isAngel = 0;
                                    $update_time = $result ? $result['update_time'] : time();
                                }

                                $defend_money = $hadMoney;
                            } else {
                                $angel = M('user_defend')->where(['to_user' => $userid, 'angel' => 1])->find();

                                if (($angel['money'] < $result['money']) && $angel['user_id'] != $touserid) {

                                    M('user')->where(['id' => $userid])->setField('angel', $touserid);
                                    M('user_defend')->where(['user_id' => ['neq', $touserid], 'to_user' => $userid])->save(['angel' => 0, 'update_time' => $update_time]);

                                    $isAngel = 1;
                                    $update_time = time();
                                } else {
                                    $isAngel = 0;
                                    $update_time = $angel['update_time'];
                                }

                                $defend_money = $result['money'];
                            }

                            if ($result) {
                                M('user_defend')->where(['id' => $result['id']])->save(['angel' => $isAngel, 'money' => $defend_money, 'update_time' => $update_time]);
                            } else {
                                M('user_defend')->add([
                                    'user_id' => $touserid,
                                    'to_user' => $userid,
                                    'money' => $defend_money,
                                    'angel' => $isAngel,
                                    'create_time' => time(),
                                    'update_time' => time(),
                                ]);
                            }*/
                        }


                    } else if ($userInfo['sex'] == '女' && $touserid_privacy != $kefu && $userInfo['id'] != $kefu) {
                        $msg_1 = "当前聊天是你付费，如要改成对方付费请点击右下方'+'->'换TA付费'按钮";
                        $contain = ["userid" => $touserid_privacy, "touserid" => $userid_privacy, "type" => -1, "content" => $msg_1, 'finish' => 1, 'single' => 1];
                        $hasTip = M('privatechat')->where($contain)->where(['addtime'=>['gt',date('Y-m-d H:i:s', strtotime('-1 hours'))]])->find();
                        if (!$hasTip) {
                            $pushNewMsgs[] = $contain;
                        }
                    }

                    //---------------------------

                    // 魅力值
                    if ($money + 0) {
                        M('user')->where(['id' => $userid_privacy])->setInc('tycoon', $money * 1);
                    }
                }else{
                    $IncOk = true;
                }
            }else{
                $IncOk = true;
            }
            if($type != 8){
                $pushNewMsgs[0]['front_id'] = $front_id;
            }
            $payer_id = $recharge_user['id'] == $userid ? $userid_privacy : $touserid_privacy;
            foreach ($pushNewMsgs as $pmk => $pmv) {
                $pushNewMsgs[$pmk]['up'] = 0;
                if(isset($pmv['id']) && $type != 8){
                    if(!isset($pmv['type'])){
                        $pushNewMsgs[$pmk]['type'] = 0;
                    }
                    $pushNewMsgs[$pmk]['up'] = 1;
                    continue;
                }
                if($type == 8 && $pmk == 0){
                    continue;
                }

                $user_device_id_key = $pmv['userid'] == $userid_privacy?'u_d_id':'t_d_id';
                if (isset($pmv['data']) && $pmv['data'] && strpos($pmv['data'], '{') === 0) {
                    $pmv['data'] = json_decode($pmv['data'], true);
                    $pmv['data'][$user_device_id_key] = $userInfo_privacy['device_id'];
                    $chat_data_o = $pmv['data'];
                } else if (isset($pmv['data']) && $pmv['data']) {
                    $chat_data_o = [$user_device_id_key => $userInfo_privacy['device_id'], 'value'=>$pmv['data']];
                } else {
                    $chat_data_o = [$user_device_id_key => $userInfo_privacy['device_id']];
                }

                if (isset($pmv['score']) && $pmv['score']) {
                    if ($userInfo['volley_gift']>0) {
                        $use_volley_gift = $pmv['score'] > $userInfo['volley_gift'] ? $userInfo['volley_gift'] : $pmv['score'];
                        $pmv['score'] = $pmv['score'] - $use_volley_gift;
                        $userInfo['volley_gift']-=$use_volley_gift;
                    }
                    $chat_data_o['payer'] = $payer_id;
                }

                $pmv['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                $pmv['send_sex'] = $userInfo['sex'];
                $pmv['ip'] = getClientIP();
                $msgid = M('privatechat')->add($pmv);
                $pushNewMsgs[$pmk]['id'] = $msgid;
                $pmv['id'] = $msgid;
                $TencentIMResponse = (new TencentIM)->sendmsg($pmv['userid'], $pmv['touserid'], $pmv['content']??'', $pmv, $pmv['single']??0);
                $chat_data_o['MsgKey'] = $TencentIMResponse['MsgKey']??'';
                $pmv['data'] = json_encode($chat_data_o, JSON_UNESCAPED_UNICODE);
                M('privatechat')->save($pmv);
            }
            if ($privatechat_free && $chat_free) {
                $chatfreeSeeder = $privatechat_free['server'] == $userid ? 'seller_msg' : 'buyer_msg';
                M('privatechat_free')->where(['id'=>$privatechat_free['id']])->setInc($chatfreeSeeder);
            }
            if($IncOk){
                M()->commit();
            }else{
                M()->rollback();
                exit(json_encode(['code' => 400, 'msg' => '服务繁忙']));
            }

            if(in_array($type, [0, 12, 20, 22])){
                // 预警词记录
                if ($kefu != $userid && $kefu != $touserid_privacy) {
                    $warnWord = M('chat_warn_word')->where(['is_hidden' => 0])->cache(true)->getField('id, title');
                    foreach ($warnWord as $k => $v) {
                        if (stripos($pushNewMsgs[0]['content'], $v) !== false) {
                            M('chat_warn')->add(['user_id' => $userid_privacy, 'word_id' => $k, 'chat_id' => $pushNewMsgs[0]['id'], 'create_time' => time()]);
                            break;
                        }
                    }
                }
            }

            // 清除聊天缓存
            // S("getMsgList$userid&$touserid",null);
            // S("getMsgList$touserid&$userid",null);



            if ($userid != $kefu && !$greet && !$notice && in_array($type, [0, 12])) {
                // 任务
                D('Task')->finish('word_chat', $userid);
            }

            if(!$system_greet) {

                foreach ($pushNewMsgs as $pmk => $pmv) {
                    if ($pmv['up'] == 1) continue;
                    // if ($pmv['single'] == 2) {
                    //     $pushNewMsgs[$pmk]['single'] = 0;
                    // }
                    $pmv['payer_id'] = $payer_id;
                    $this->pushNewMsg($pmv);
                }
                // $this->getNewMsg(json_encode(['userid' => $userid, 'touserid' => $touserid]));
                $this->getOtherList(json_encode(['userid' => $touserid_privacy, 'count' => '', 'type' => '']));
                // 推送
                if(!$touserInfo['unpush'] && (!isset($pushNewMsgs[0]['single']) || $pushNewMsgs[0]['single'] != 2)){
                    $datas = json_encode(['type' => 2, 'userid' => $userid_privacy, 'name' => $userInfo_privacy['name'], 'privacy'=> $userInfo_privacy['reg'] == 2 ? 1 : 0], JSON_UNESCAPED_UNICODE);
                    D('Push')->send(2, $touserid, $userInfo_privacy['name'], $msg, $datas);
                }
                if (!$timing && !$fate && $userid != $kefu && $touserid != $kefu && $touserInfo['sex'] == '女' && $userInfo['sex'] == '男') {
                    $hasWelFare = M('welfare')->master(true)->where(['user_id'=>$touserid, 'state'=>1])->find();
                    if($hasWelFare){
                        $interactUserIds = $hasWelFare['interact_user_ids'] ? explode(',',$hasWelFare['interact_user_ids']) : [];
                        if(!in_array($userid, $interactUserIds)){
                            $interactUserIds[] = $userid;
                            if($hasWelFare['interact'] == sizeof($interactUserIds)){
                                M('welfare')->where(['id'=>$hasWelFare['id']])->save(['state'=>0, 'interact_user_ids'=>implode(',',$interactUserIds)]);
                                M('wallet_frozen')->where(['user_id'=>$touserid])->setDec('value', $hasWelFare['value']);
                                M('wallet_frozen_records')->add(['user_id'=>$touserid, 'value'=>$hasWelFare['value'], 'time'=>time(), 'remark'=>'系统赠送积分(新用户福利) 任务完成', 'type'=>1]);
                                if(isset($config['welfare_score_over_tip']) && $config['welfare_score_over_tip']){
                                    $welfareChat = [
                                        'userid' => $kefu,
                                        'touserid' => $touserid,
                                        'content' => $config['welfare_score_over_tip'],
                                        'data' => '',
                                        'k' => 0,
                                        'single' => 1
                                    ];
                                    $chat = M('privatechat')->add($welfareChat);
                                    if($chat){
                                        D('ChatLists')->updateLists($kefu, $touserid, 1, 0, $welfareChat['content'], 0);
                                        $this->pushNewMsg($welfareChat);
                                    }
                                }
                            }else{
                                M('welfare')->where(['id'=>$hasWelFare['id']])->save(['interact_user_ids'=>implode(',',$interactUserIds)]);
                            }
                        }
                    }
                }
            }

            $this->getOtherList(json_encode(['userid' => $userid_privacy, 'count' => '', 'type' => '']));

            if ($timing) {
                $this->getreadcount(json_encode(['user_id' => $touserid]));
            }

            if($return && $pushNewMsgs[0]){
                if(!isset($intimate)){
                    $intimate = M('user_intimate')->where(['couple_a' => $couple_a])->getField('intimate');
                }
                $pushNewMsgs[0]['intimate'] = $intimate;
                exit(json_encode(['code'=>200,'data'=>$pushNewMsgs[0], 'payer_id'=>$payer_id]));
            }


        }
    }


    private function dayFreeChat($userid, $touserid)
    {
        $redis = new \Redis();
        $redis->connect('127.0.0.1',getenv('REDIS_PORT'));
        if(getenv('REDIS_PASS')){
            $redis->auth(getenv('REDIS_PASS'));
        }
        $redis->select(9);
        $date = date('Y-m-d');

        $freeUsersKey = "user:{$userid}:freeUsers:{$date}";
        // 检查用户是否已经在免费聊天对象列表中
        if (!$redis->sismember($freeUsersKey, $touserid)) {
            // 如果不在列表中，检查是否已经达到最大免费聊天对象数量
            if ($redis->scard($freeUsersKey) >= 5) {
                return false;
            }

            // 添加到免费聊天对象列表
            $redis->sadd($freeUsersKey, $touserid);

            // 设置过期时间为一天
            $redis->expire($freeUsersKey, 86400);
        }

        $chatCountKey = "user:{$userid}:chatWith:{$date}:{$touserid}:count";

        // 获取当前计数
        $currentCount = (int) $redis->hget($chatCountKey, 'count');

        // 检查是否超过免费次数
        if ($currentCount >= 1) {
            return false;
        }

        // 更新计数
        $redis->hincrby($chatCountKey, 'count', 1);

        // 设置过期时间为一天
        $redis->expire($chatCountKey, 86400);

        return true;
    }
    // 不走数据库推送新消息
    private function pushNewMsg($data)
    {
        $userid = $data['userid'];
        $touserid = $data['touserid'];
        $result = $data;

        // if(isset($result['single']) && $result['single'] == 2){ return; }
        if(!isset($result['type'])){ $result['type'] = 0; }
        if(!isset($result['status'])){ $result['status'] = "0"; }
        if(!isset($result['state'])){ $result['state'] = "0"; }
        if(!isset($result['second'])){ $result['second'] = "0"; }
        if(!isset($result['is_burn'])){ $result['is_burn'] = "0"; }
        if(!isset($result['k'])){ $result['k'] = "0"; }
        if(!isset($result['money'])){ $result['money'] = '0.00'; }
        if(!isset($result['score'])){ $result['score'] = '0.00'; }
        if(!isset($result['location'])){ $result['location'] = "0"; }
        if(!isset($result['isRead'])){ $result['isRead'] = "0"; }
        if(!isset($result['isCount'])){ $result['isCount'] = "0"; }
        if(!isset($result['sound_tip'])){ $result['sound_tip'] = "0"; }
        if(!isset($result['sms_tip'])){ $result['sms_tip'] = "0"; }
        if(!isset($result['is_public'])){ $result['is_public'] = "0"; }
        if(!isset($result['is_fate'])){ $result['is_fate'] = "0"; }
        if(!isset($result['order_id'])){ $result['order_id'] = "0"; }
        if(!isset($result['front_id']) || $result['front_id']==0){ $result['front_id'] = ""; }
        if(!isset($result['addtime'])){ $result['addtime'] = date('Y-m-d H:i:s'); }

        $data = ['new' => [], 'recall' => [], 'users' => ['userid' => $touserid, 'touserid' => $userid, 'intimate' => 0]];
    
        $users = M('user')->where(['id' => ['in', [$userid, $touserid]]])->cache(true,86400)->getField('id, name, head_100, head_portrait, sex, quality, reg, authcode');


        if ($result) {
            $result['self'] = $userid == $result['userid'] ? 1 : 0;

            $result['name'] = $users[$result['userid']]['name'];
            $result['head_portrait'] = $users[$result['userid']]['head_portrait'];

            $datas = json_decode($result['data'], true);

            if (isset($datas['image'])) {
                $datas['image'] = changeUrl($datas['image']);
            }

            if (in_array($result['type'], [9, 10])) {
                if (isset($datas['status']) && $datas['status']) {
                    if (isset($datas['start']) && isset($datas['end'])) {
                        $chat_time = $datas['end'] - $datas['start'];
                        $result['chat_time'] = changeTime($chat_time);
                    } else {
                        if ($datas['second']) {
                            $result['content'] .= changeTime($datas['second'] * 60);
                        } else {
                            $result['content'] .= '00:59';
                        }
                    }
                    if($result['type'] == 9){
                        D('UserActiveval')->inc($userid, 'chatforaudio');
                    }else{
                        D('UserActiveval')->inc($userid, 'chatforvideo');
                    }
                } else {
                    $result['content'] .= ' 未接通';
                }
            }else{
                // D('UserActiveval')->inc($userid, 'chatformsg');
            }

            $result['data'] = $datas;

            $data['new'][] = $result;

            $couple_a = $userid < $touserid ? $userid . ',' . $touserid : $touserid . ',' . $userid;
            $intimate = M('user_intimate')->where(['couple_a' => $couple_a])->getField('intimate');

            $data['users']['intimate'] = $intimate ?$intimate / 10: 0;
        }

        $contain = $data;
        foreach ($contain['new'] as $k => $v) {
            $v['self'] = $v['self'] ? 0 : 1;
            $contain['new'][$k] = $v;
        }

        if (!empty($data['new']) || !empty($data['recall'])) {
            if (isset($result[0]) && $result[0]['single']) {
                $data = [];
            }
            $message1 = json_encode(['code' => 200, 'v' => 1, 'action' => 'Home/Privatechat/getNewMsg', 'data' => $contain, 'user_id'=>$touserid]);
            $message2 = json_encode(['code' => 200, 'v' => 1, 'action' => 'Home/Privatechat/getNewMsg', 'data' => $data, 'user_id'=>$userid]);
        } else {
            $message1 = $message2 = json_encode(['code' => 400, 'v' => 1, 'action' => 'Home/Privatechat/getNewMsg', 'data' => []]);
        }
        if ($result['type'] == 8 && $users[$result['userid']]['sex'] == '女' && $users[$result['userid']]['quality'] < 2 && $result['money'] <= 0) {

        } else if (!isset($result['single']) || $result['single'] != 2) {
            if ($users[$touserid]['reg'] == 2) {
                $touserid = M('user')->where(['id'=>$users[$touserid]['authcode']])->getField('id');
            }
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $message1);
        }
        if($result['single']==0 || $result['single']==2){
            if ($users[$userid]['reg'] == 2) {
                $userid = M('user')->where(['id'=>$users[$userid]['authcode']])->getField('id');
            }
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid, $message2);
        }
    }


    // 获取新消息
    public function getNewMsg($data)
    {
        $data = json_decode($data, true);

        $userid = $data['userid'];
        $touserid = $data['touserid'];

        $type = isset($data['type']) ? " = " . $data['type'] : " <> -1";

        $Model = M();

        $data = ['new' => [], 'recall' => [], 'users' => ['userid' => $touserid, 'touserid' => $userid, 'intimate' => 0]];
    
        $users = M('user')->where(['id' => ['in', [$userid, $touserid]]])->cache(true, 86400)->getField('id, name, head_100, head_portrait, sex');

        /*$sql = <<<sql
            SELECT t.*, t1.head_100 as head_portrait, t1.name, t.addtime FROM privatechat t, user t1 
            WHERE t.userid = $userid  AND t.touserid = $touserid and t.status not in (-1,2) AND t.isRead = 0 AND (t.type $type AND t.state <> 1) AND t.userid = t1.id 
            ORDER BY t.id desc limit 0,1
sql;*/
    
        $sql = <<<sql
            SELECT t.* FROM privatechat t
            WHERE userid = $userid  AND touserid = $touserid and status not in (-1,2) AND isRead = 0 AND (type $type AND state <> 1)
            ORDER BY id desc limit 0,1
sql;
        $result = $Model->Query($sql);

        if ($result) {
            foreach ($result as $key => $item) {
                $result[$key]['self'] = $userid == $item['userid'] ? 1 : 0;
    
                $result[$key]['name'] = $users[$item['userid']]['name'];
                $result[$key]['head_portrait'] = $users[$item['userid']]['head_portrait'];

                $datas = json_decode($item['data'], true);

                if (isset($datas['image'])) {
                    $datas['image'] = changeUrl($datas['image']);
                }

                if (in_array($item['type'], [9, 10])) {
                    if (isset($datas['status']) && $datas['status']) {
                        if (isset($datas['start']) && isset($datas['end'])) {
                            $chat_time = $datas['end'] - $datas['start'];
                            $result[$key]['chat_time'] = changeTime($chat_time);
                        } else {
                            if ($datas['second']) {
                                $result[$key]['content'] .= changeTime($datas['second'] * 60);
                            } else {
                                $result[$key]['content'] .= '00:59';
                            }
                        }
                    } else {
                        $result[$key]['content'] .= ' 未接通';
                    }
                }

                $result[$key]['data'] = $datas;
            }

            $data['new'] = $result;

            $couple_a = $userid < $touserid ? $userid . ',' . $touserid : $touserid . ',' . $userid;
            $intimate = M('user_intimate')->where(['couple_a' => $couple_a])->getField('intimate');

            $data['users']['intimate'] = $intimate ?: 0;
        }

        // 消息撤回提示
        $ids = M('privatechat')->where(['userid' => $touserid, 'touserid' => $userid, 'status' => 3, 'isRead' => 0])->getField('id', true);
        if ($ids) {
            $data['recall'] = $ids;
            foreach ($ids as $val){
                M('privatechat')->where(['id'=>$val])->save(['isRead' => 1]);
            }
            // M('privatechat')->where(['id' => ['in', $ids]])->save(['isRead' => 1]);
            /*// 更新会话列表
            D('ChatLists')->changeLists($userid, $touserid);*/
        }



    //   if (!empty($users)){
    //         if ($users[$userid]['sex'] =='女'){
    //             $config_personal=M('config_personal')->where(['user_id'=>(int)$userid])->field('voice_price,video_price')->find();
    //         }else{
    //             $config_personal=M('config_personal')->where(['user_id'=>(int)$touserid])->field('voice_price,video_price')->find();
    //         }
    //         if (isset($data['new'][0]['type']) && $data['new'][0]['type'] ==9 && $config_personal){
    //             $price = $config_personal['voice_price'];
    //         }elseif (isset($data['new'][0]['type']) && $data['new'][0]['type'] ==10 && $config_personal){
    //             $price = $config_personal['video_price'];
    //         }else{
    //             if (isset($data['new'][0]['type']) && $data['new'][0]['type'] ==9){
    //                 $priceInfo=M('config_system')->where(['title'=>'voice_price'])->field('content')->find();
    //                 $price=$priceInfo['content'];
    //             }elseif (isset($data['new'][0]['type']) && $data['new'][0]['type'] ==10){
    //                 $priceInfo=M('config_system')->where(['title'=>'video_price'])->field('content')->find();
    //                 $price=$priceInfo['content'];
    //             }else{
    //                 $price =0;
    //             }
    //         }
    //     }else{
    //         $price =0;
    //     }
    //     if (isset($data['new'][0]['data']['start']) && isset($data['new'][0]['data']['end'])){
    //         $use_time =ceil(($data['new'][0]['data']['end']-$data['new'][0]['data']['start'])/60) ;

    //         $data['new'][0]['data']['score'] =$use_time*$price;
    //         $data['new'][0]['score'] =$use_time*$price;
    //     }

        $contain = $data;
        foreach ($contain['new'] as $k => $v) {
            $v['self'] = $v['self'] ? 0 : 1;
            $contain['new'][$k] = $v;
        }

        if (!empty($data['new']) || !empty($data['recall'])) {
            if (isset($result[0]) && $result[0]['single']) {
                $data = [];
            }
            $message1 = json_encode(['code' => 200, 'action' => 'Home/Privatechat/getNewMsg', 'data' => $contain]);
            $message2 = json_encode(['code' => 200, 'action' => 'Home/Privatechat/getNewMsg', 'data' => $data]);
        } else {
            $message1 = $message2 = json_encode(['code' => 400, 'action' => 'Home/Privatechat/getNewMsg', 'data' => []]);
        }

        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $message1);   // 发送方
        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid, $message2);     // 接收方
    }
    // 获取新消息
    public function getNewMsgold($data)
    {
        $data = json_decode($data, true);

        $userid = $data['userid'];
        $touserid = $data['touserid'];

        $type = isset($data['type']) ? " = " . $data['type'] : " <> -1";

        $Model = M();

        $data = ['new' => [], 'recall' => [], 'users' => ['userid' => $touserid, 'touserid' => $userid, 'intimate' => 0]];
    
        // $users = M('user')->where(['id' => ['in', [$userid, $touserid]]])->cache(true, 86400)->getField('id, name, head_100, head_portrait, sex');
        
        $user1 = M('user')->where(['id' =>(int)$userid])->cache(true, 86400)->field('id, name, head_100, head_portrait, sex')->find();
        $user2 = M('user')->where(['id' =>(int)$touserid])->cache(true, 86400)->field('id, name, head_100, head_portrait, sex')->find();
        $users[$userid] = $user1;
        $users[$touserid] = $user2;

        /*$sql = <<<sql
            SELECT t.*, t1.head_100 as head_portrait, t1.name, t.addtime FROM privatechat t, user t1 
            WHERE t.userid = $userid  AND t.touserid = $touserid and t.status not in (-1,2) AND t.isRead = 0 AND (t.type $type AND t.state <> 1) AND t.userid = t1.id 
            ORDER BY t.id desc limit 0,1
sql;*/
    
        $sql = <<<sql
            SELECT t.* FROM privatechat t
            WHERE userid = $userid  AND touserid = $touserid and status not in (-1,2) AND isRead = 0 AND (type $type AND state <> 1)
            ORDER BY id desc limit 0,1
sql;
        $result = $Model->Query($sql);

        if ($result) {
            foreach ($result as $key => $item) {
                $result[$key]['self'] = $userid == $item['userid'] ? 1 : 0;
    
                $result[$key]['name'] = $users[$item['userid']]['name'];
                $result[$key]['head_portrait'] = $users[$item['userid']]['head_portrait'];

                $datas = json_decode($item['data'], true);

                if (isset($datas['image'])) {
                    $datas['image'] = changeUrl($datas['image']);
                }

                if (in_array($item['type'], [9, 10])) {
                    if (isset($datas['status']) && $datas['status']) {
                        if (isset($datas['start']) && isset($datas['end'])) {
                            $chat_time = $datas['end'] - $datas['start'];
                            $result[$key]['chat_time'] = changeTime($chat_time);
                        } else {
                            if ($datas['second']) {
                                $result[$key]['content'] .= changeTime($datas['second'] * 60);
                            } else {
                                $result[$key]['content'] .= '00:59';
                            }
                        }
                    } else {
                        $result[$key]['content'] .= ' 未接通';
                    }
                }

                $result[$key]['data'] = $datas;
            }

            $data['new'] = $result;

            $couple_a = $userid < $touserid ? $userid . ',' . $touserid : $touserid . ',' . $userid;
            $intimate = M('user_intimate')->where(['couple_a' => $couple_a])->getField('intimate');

            $data['users']['intimate'] = $intimate ?: 0;
        }

        // 消息撤回提示
        $ids = M('privatechat')->where(['userid' => $touserid, 'touserid' => $userid, 'status' => 3, 'isRead' => 0])->getField('id', true);
        if ($ids) {
            $data['recall'] = $ids;
            foreach ($ids as $val){
                M('privatechat')->where(['id'=>$val])->save(['isRead' => 1]);
            }
            // M('privatechat')->where(['id' => ['in', $ids]])->save(['isRead' => 1]);
            /*// 更新会话列表
            D('ChatLists')->changeLists($userid, $touserid);*/
        }



    //   if (!empty($users)){
    //         if ($users[$userid]['sex'] =='女'){
    //             $config_personal=M('config_personal')->where(['user_id'=>(int)$userid])->field('voice_price,video_price')->find();
    //         }else{
    //             $config_personal=M('config_personal')->where(['user_id'=>(int)$touserid])->field('voice_price,video_price')->find();
    //         }
    //         if (isset($data['new'][0]['type']) && $data['new'][0]['type'] ==9 && $config_personal){
    //             $price = $config_personal['voice_price'];
    //         }elseif (isset($data['new'][0]['type']) && $data['new'][0]['type'] ==10 && $config_personal){
    //             $price = $config_personal['video_price'];
    //         }else{
    //             if (isset($data['new'][0]['type']) && $data['new'][0]['type'] ==9){
    //                 $priceInfo=M('config_system')->where(['title'=>'voice_price'])->field('content')->find();
    //                 $price=$priceInfo['content'];
    //             }elseif (isset($data['new'][0]['type']) && $data['new'][0]['type'] ==10){
    //                 $priceInfo=M('config_system')->where(['title'=>'video_price'])->field('content')->find();
    //                 $price=$priceInfo['content'];
    //             }else{
    //                 $price =0;
    //             }
    //         }
    //     }else{
    //         $price =0;
    //     }
    //     if (isset($data['new'][0]['data']['start']) && isset($data['new'][0]['data']['end'])){
    //         $use_time =ceil(($data['new'][0]['data']['end']-$data['new'][0]['data']['start'])/60) ;

    //         $data['new'][0]['data']['score'] =$use_time*$price;
    //         $data['new'][0]['score'] =$use_time*$price;
    //     }

        $contain = $data;
        foreach ($contain['new'] as $k => $v) {
            $v['self'] = $v['self'] ? 0 : 1;
            $contain['new'][$k] = $v;
        }

        if (!empty($data['new']) || !empty($data['recall'])) {
            if (isset($result[0]) && $result[0]['single']) {
                $data = [];
            }
            $message1 = json_encode(['code' => 200, 'action' => 'Home/Privatechat/getNewMsg', 'data' => $contain]);
            $message2 = json_encode(['code' => 200, 'action' => 'Home/Privatechat/getNewMsg', 'data' => $data]);
        } else {
            $message1 = $message2 = json_encode(['code' => 400, 'action' => 'Home/Privatechat/getNewMsg', 'data' => []]);
        }

        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $touserid, $message1);   // 发送方
        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $userid, $message2);     // 接收方
    }

    // 聊天已读处理
    public function hadread()
    {
        $user_id = I('user_id');
        $touserid = I('touserid');

        try {
            M('privatechat')->where(['user_id' => $user_id, 'touserid' => $touserid])->setField('isRead', 1);

            // 更新会话列表
            D('ChatLists')->changeLists($user_id, $touserid);
        } catch (\Exception $e) {
            return json_encode(['code' => 201, 'msg' => $e->getMessage()]);
        }

        return json_encode(['code' => 200, 'msg' => 'success']);
    }

    // 从聊天列表删除对话
    public function delChat()
    {
        $uid = I('uid');
        $touid = I('touid');

        if (!$uid || !$touid) {
            echo json_encode(['code' => 201, 'msg' => '参数 uid 或 touid 有误']);
            exit();
        }

        $res = M('del_chat')->add(['uid' => $uid, 'to_uid' => $touid]);

        (new TencentIM)->recentcontact_delete($uid, $touid);

        if ($res) {
            M('privatechat')->where(['userid' => $touid, 'touserid' => $uid])->save(['isRead' => 1, 'isCount' => 1]);
            M('privatechat')->where(['userid' => $touid, 'touserid' => $uid, 'status'=>1])->save(['status' => 4]);
            M('privatechat')->where(['userid' => $touid, 'touserid' => $uid, 'status'=>0])->save(['status' => 2]);
            M('privatechat')->where(['userid' => $uid, 'touserid' => $touid, 'status'=>2])->save(['status' => 4]);
            M('privatechat')->where(['userid' => $uid, 'touserid' => $touid, 'status'=>0])->save(['status' => 1]);


            $systemhichat = M('privatechat')->where(['type'=>0,'userid'=>$touid, 'touserid'=>$uid, 'is_public'=>0, 'front_id'=>''])->find();
            if ($systemhichat && $systemhichat['content'] != '我在这儿呢') {
                $hasReply = M('privatechat')->where(['userid'=>$uid, 'touserid'=>$touid, 'single'=>0])->find();
                if (!$hasReply) {
                    $key = $uid < $touid ? 'another' : 'user';
                    M('chat_lists')->where([$key.'_id'=>$touid, ($key=='user'?'another':'user').'_id'=>$uid])->save([$key.'_first'=>1]);
                }
            }

            // 更新会话列表
            D('ChatLists')->changeLists($uid, $touid, 'delete', 1);

            $cloudList = true;
            while ($cloudList) {
                $list = (new TencentIM)->admin_getroammsg($uid, $touid);
                if (isset($list['MsgList']) && sizeof($list['MsgList'])) {
                    (new TencentIM)->delete_c2c_msg_ramble($uid, $touid, array_column($list['MsgList'], 'MsgKey'));
                } else {
                    $cloudList = false;
                }
            }

            $this->getreadcount(json_encode(['user_id' => $uid]));

            echo json_encode(['code' => 200, 'msg' => 'success']);
            exit();
        } else {
            echo json_encode(['code' => 201, 'msg' => 'error']);
            exit();
        }
    }

    public function getcurl($url, $datas)
    {
        $curl = curl_init();

        curl_setopt_array($curl, array(
            CURLOPT_URL => $url,
            CURLOPT_RETURNTRANSFER => true,
            CURLOPT_ENCODING => "",
            CURLOPT_HTTP_VERSION => CURL_HTTP_VERSION_1_1,
            CURLOPT_CUSTOMREQUEST => "POST",
            CURLOPT_POSTFIELDS => $datas,
            CURLOPT_HTTPHEADER => array(
                "Content-Type:application/x-www-form-urlencoded"
            ),
        ));

        $response = curl_exec($curl);

        $err = curl_error($curl);

        curl_close($curl);

        if ($err) {
            return ['code' => 400, 'msg' => "cURL Error #:" . $err];
        } else {
            return ['code' => 200, 'data' => $response];
        }
    }

    //-----------------------------------------------------------------

    // 消息撤回
    public function recall()
    {
        $chat_id = I('chat_id');    # 聊天消息id
        $user_id = I('user_id');    # 用户id

        if (!$chat_id || !$user_id) exit(json_encode(['code' => 201, 'msg' => '操作有误']));

        $data = M('privatechat')->where(['id' => $chat_id])->find();
        $touserid = $data['touserid'];

        if (!$data) exit(json_encode(['code' => 201, 'msg' => '消息不存在']));
        if ($data['userid'] != $user_id) exit(json_encode(['code' => 201, 'msg' => '无权操作']));
        if (in_array($data['status'], [1, 3])) exit(json_encode(['code' => 201, 'msg' => '操作有误']));
        if ($data['type'] == 5) exit(json_encode(['code' => 201, 'msg' => '红包消息无法撤回']));
        if ((strtotime($data['addtime']) + 30) <= time()) exit(json_encode(['code' => 201, 'msg' => '消息发出30秒后无法撤回']));

        try {
            M('privatechat')->where(['id' => $chat_id])->save(['status' => 3, 'type' => -1, 'isRead' => 0]);
            $data_json = json_decode($data['data'], true);
            if (isset($data_json['MsgKey'])) {
                (new TencentIM)->admin_msgwithdraw($user_id, $touserid, $data_json['MsgKey']);
            }
        } catch (Exception $e) {
            exit(json_encode(['code' => 201, 'msg' => $e->getMessage()]));
        }

        // 更新会话列表
        D('ChatLists')->changeLists($user_id, $touserid, 'recall');

        /*// 清除聊天缓存
        S("getMsgList$user_id&$touserid",null);
        S("getMsgList$touserid&$user_id",null);*/

        $this->getNewMsg(json_encode(['userid' => $data['touserid'], 'touserid' => $user_id]));
        $this->getOtherList(json_encode(['userid' => $data['touserid'], 'count' => '', 'type' => '']));

        exit(json_encode(['code' => 200, 'msg' => '已撤回']));
    }

    // 消息删除
    public function delete()
    {
        $chat_id = I('chat_id');    # 消息id
        $user_id = I('user_id');    # 用户id
        $to_user = I('to_user');    # 用户id

        if (!$chat_id && $to_user) {
            $data = M('privatechat')->where(['userid' => $user_id, 'touserid' => $to_user, 'status' => ['in', [-1,0,2]]])->select();

            $conDel = [];
            $conUpdate = [];
            foreach ($data as $key => $item) {
                if ($item['status'] == 2) {
                    $conDel[] = $item['id'];
                } else {
                    $conUpdate[] = $item['id'];
                }
            }

            if ($conDel) {
                M('privatechat')->where(['id' => ['in', $conDel]])->setField('status', 4);
            }

            if ($conUpdate) {
                M('privatechat')->where(['id' => ['in', $conUpdate]])->setField('status', 1);
            }

            $data = M('privatechat')->where(['userid' => $to_user, 'touserid' => $user_id, 'status' => ['in', [-1,0,1]]])->select();

            $conDel = [];
            $conUpdate = [];
            foreach ($data as $key => $item) {
                if ($item['status'] == 1) {
                    $conDel[] = $item['id'];
                } else {
                    $conUpdate[] = $item['id'];
                }
            }

            if ($conDel) {
                M('privatechat')->where(['id' => ['in', $conDel]])->setField('status', 4);
            }

            if ($conUpdate) {
                M('privatechat')->where(['id' => ['in', $conUpdate]])->setField('status', 2);
            }

            $delChat = M('del_chat')->where(['uid' => $user_id, 'to_uid' => $to_user])->find();

            if (!$delChat) {
                M('del_chat')->add(['uid' => $user_id, 'to_uid' => $to_user]);
            }
    
            // 撤回消息
            M('privatechat')->where(['type' => -1, 'userid' => $user_id, 'touserid' => $to_user, 'status' => 3])->setField('status', 4);

            $msg = '已清空';

            // 更新会话列表
            D('ChatLists')->changeLists($user_id, $to_user, 'delete_all');

        } else if ($chat_id && !$to_user) {
            $chat_id = explode(',', $chat_id);

            //$data = M('privatechat')->where(['id' => $chat_id[0]])->find();

            $data = M('privatechat')->where(['id' => ['in', $chat_id]])->select();

            $conDel = [];
            $status_1 = [];
            $status_2 = [];
            foreach ($data as $key => $item) {
                if ($item['userid'] == $user_id) {
                    if ($item['status'] == 2) {
                        $conDel[] = $item['id'];
                    } else {
                        $status_1[] = $item['id'];
                    }
                } else {
                    if ($item['status'] == 1) {
                        $conDel[] = $item['id'];
                    } else {
                        $status_2[] = $item['id'];
                    }
                }
            }

            if ($conDel) {
                M('privatechat')->where(['id' => ['in', $conDel]])->setField('status', 4);
            }

            if ($status_1) {
                M('privatechat')->where(['id' => ['in', $status_1]])->setField('status', 1);
            }

            if ($status_2) {
                M('privatechat')->where(['id' => ['in', $status_2]])->setField('status', 2);
            }

            $msg = '已删除';

            if ($data[0]) {
                $to_user = $data[0]['userid'] == $user_id ? $data[0]['touserid'] : $data[0]['userid'];

                // 更新会话列表
                D('ChatLists')->changeLists($user_id, $to_user, 'delete_one');
            }


            /*if (!$data) exit(json_encode(['code' => 201, 'msg' => '消息不存在']));

            if ($data['userid'] == $user_id) { # 发送方删除
                if (in_array($data['status'], [1, 3])) exit(json_encode(['code' => 201, 'msg' => '无权操作']));
                $status = 1;
            } else if ($data['touserid'] == $user_id) { # 接收方删除
                if (in_array($data['status'], [2, 3])) exit(json_encode(['code' => 201, 'msg' => '无权操作']));
                $status = 2;
            } else {
                exit(json_encode(['code' => 201, 'msg' => '无权操作']));
            }

            M('privatechat')->where(['id' => ['in', $chat_id]])->save(['status' => $status]);*/
        }

        // 清除聊天缓存
        // S("getMsgList$user_id&$to_user",null);
        // S("getMsgList$to_user&$user_id",null);

        exit(json_encode(['code' => 200, 'msg' => $msg]));
    }

    // 领取红包
    public function receive()
    {
        $chat_id = I('chat_id');    # 聊天消息id
        $user_id = I('user_id');    # 用户id

        if (!$chat_id || !$user_id) exit(json_encode(['code' => 201, 'msg' => '操作有误']));

        $data = M('privatechat')->where(['id' => $chat_id, 'type' => ['in', [5, 7]], 'status' => ['not in', [-1, 3]], 'state' => 0])->find();

        if (!$data) exit(json_encode(['code' => 201, 'msg' => '红包消息不存在']));

        if ($data['touserid'] != $user_id) exit(json_encode(['code' => 201, 'msg' => '无权操作']));

        // 红包金额
        $money = M('order_common')->where(['data' => '{"id":' . $chat_id . '}'])->getField('money');
        $name = M('user')->where(['id' => $data['userid']])->getField('name');
        $touser_name = M('user')->where(['id' => $data['touserid']])->getField('name');

        // 开启事务
        M()->startTrans();
        try {
            // 红包状态改变
            M('privatechat')->where(['id' => $chat_id])->save(['state' => 1]);
            if ($data['type'] == 7) { //现金红包
                $rate = M('config_system')->where(['title' => 'rate'])->getField('content');
                $money = $money * $rate;
            }
            M('user')->where(['id' => $user_id])->setInc('volley', $money);
            M('volley_desc')->add(['user_id' => $user_id, 'content' => '领取红包', 'price' => $money, 'types' => 1, 'time' => time()]);

            // 添加聊天
            $id = M('privatechat')->add([
                "userid" => $data['touserid'],
                "touserid" => $data['userid'],
                "type" => -1,
                "content" => '领取红包',
                "data" => json_encode([
                    'chat_id' => $chat_id,
                    'userid' => $data['userid'],
                    'user_name' => $name,
                    'touserid' => $data['touserid'],
                    'touser_name' => $touser_name,
                    'type' => $data['type']
                ]),
                "state" => 1,
            ]);

            M()->commit();//提交
        } catch (\Exception $e) {
            M()->rollback();//回滚
            exit(json_encode(['code' => 201, 'msg' => $e->getMessage()]));
        }

        exit(json_encode(['code' => 200, 'msg' => '领取成功']));
    }

    // 红包详情
    public function details()
    {
        $chat_id = I('chat_id');    # 聊天消息id

        if (!$chat_id) exit(json_encode(['code' => 201, 'msg' => '操作有误']));

        $data = M('privatechat')
            ->field('id, userid, content, state')
            ->where(['id' => $chat_id, 'type' => ['in', [5, 7]], 'status' => ['not in', [-1, 3]]])
            ->find();

        if (!$data) exit(json_encode(['code' => 201, 'msg' => '红包消息不存在']));

        $user = M('user')->field('name, head_100 head')->where(['id' => $data['userid']])->find();

        // 红包金额
        $money = M('order_common')->where(['data' => '{"id":' . $chat_id . '}'])->getField('money');

        $data['money'] = $money;
        $data = array_merge($data, $user);

        exit(json_encode(['code' => 200, 'data' => $data]));
    }

    //-----------------------------------------------------------------

    // 发起语音通话请求
    public function toRequest()
    {
        $user_id = I('user_id');
        $another_id = I('another_id');
        $channel = I('channel');        // 加入的频道
        $types = I('types');            // 1语音 | 2视频
        $is_enough = I('is_enough',1);
        $orderid = I('orderid');
        $appid = getenv('TLS_APPID');

        $user_privacy = $user = M('user')->field('id, name, is_banned, banned_end_time,reg,authcode')->where(['id' => $user_id])->find();
        $another_user_privacy = $another_user = M('user')->field('id, name, is_banned, banned_end_time,reg,authcode')->where(['id' => $another_id])->find();
        if ($user['reg']==2) {
            $user = M('user')->field('id, name, is_banned, banned_end_time,reg,authcode')->where(['id' => $user_privacy['authcode']])->find();
            $another_user = M('user')->field('id, name, is_banned, banned_end_time,reg,authcode')->where(['id' => $another_user_privacy['authcode']])->find();
        }
        if ($user['is_banned']) {
        // if ($user['is_banned'] && strtotime($user['banned_end_time']) > time()) {
            exit;
        }
        $chatSingle = M('privatechat_user_single')->where(['user_id'=>$user['id']])->find();
        if ($chatSingle){
            exit;
        }
        if ($types == 2) {
            $videoBanned = M('privatechat_lianmai_video_banned')
                            ->where(['user_id'=>$user['id']])
                            ->where('expire_time >'.time())
                            ->find();
            if ($videoBanned) {
                exit;
            }
            $chatSingle = M('privatechat_lianmai_limit')->master(true)->where(['user_id'=>['in', [$user['id'], $another_user['id']]], 'banned_time'=>['GT', time()]])->find();
            // var_dump($chatSingle);exit;
            if ($chatSingle){
                exit;
            }
            $chatSingle = M('privatechat_lianmai_limit_single')->master(true)->where("(user_id=".$user['id']." and touser_id=".$another_user['id'].") or (user_id=".$another_user['id']." and touser_id=".$user['id'].")")->where(['banned_time'=>['GT', time()]])->find();
            if ($chatSingle){
                exit;
            }
        }
        $message = json_encode([
            'code' => 200,
            'action' => 'Home/Privatechat/toRequest',
            'data' => [
                'user_id' => $user_id,
                'another_id' => $another_id,
                'types' => $types,
                'channel' => $channel,
                'name' => $another_user_privacy['name'],
                'orderid' => $orderid,
                'trtc_appid'=>$appid,
                'is_enough'=>$is_enough,
                
            ]
        ]);
        Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user['id'], $message);

        $datas = json_encode([ 'is_enough'=>$is_enough,'type' => 2, 'userid' => $another_id, 'name' => $another_user_privacy['name'], 'orderid'=>$orderid, 'channel'=>$types, 'privacy'=> $another_user_privacy['reg'] == 2 ? 1 : 0, 'trtc_appid'=>$appid], JSON_UNESCAPED_UNICODE);

        if (!$another_user['unpush']) {
            D('Push')->send(2, $user['id'], $another_user_privacy['name'], '邀请你通话', $datas);
        }
    }

    // 语音通话请求结果
    public function returnRequestold()
    {
        $user_id = I('user_id');
        $another_id = I('another_id');
        $channel = I('channel');        // 加入的频道
        $status_real = $status = I('status');          // 0取消 | 1接听 | 2无权限 | 4无音频前端取消 | 5通话断开
        $types = I('types');            // 1语音 | 2视频
        $orderid = I('orderid');
        $checksocket = I('auto', 0);
        $error = 0;

        if (in_array($status_real, ['4', '5'])) {
            $status = 0;
        }

        $configs = M('config_system')->master(true)->where(['category'=>'chat'])->getField('title,content');
        $f_start = $configs['lianmai_first_start'] ?? 17;
        $f_end = $configs['lianmai_first_end'] ?? 25;
        if ($f_start >= 56 || $f_start < 5) $f_start = 17;
        if ($f_end >= 56 || $f_end < 5) $f_end = 25;
         $randSecond = rand($f_start,$f_end);
        //   $randSecond = rand(1,2);
        // $randSecond = 29;

        $user_privacy = $user = M('user')->where(['id' => $user_id])->find();
        $user_id_privacy = $user_id;
        $touser_id_privacy = $another_id;
        if ($user['reg']==2) {
            $user = M('user')->where(['id' => $user_privacy['authcode']])->find();
            $user_id = $user['id'];
            $another_id = M('user')->where(['id' => $touser_id_privacy])->getField('authcode');
        }
        $redis = new \Redis();
        $redis->connect('127.0.0.1',getenv('REDIS_PORT'));
        if(getenv('REDIS_PASS')){
            $redis->auth(getenv('REDIS_PASS'));
        }
        $time = time();
        if ($orderid) {
            $order = M('order_common')->master(true)->find($orderid);

            if ($order) {
                $order_data = $data = json_decode($order['data'], true);
                if ($order_data && in_array($status, [0, 2]) && isset($order_data['start'])) {
                    if (isset($order_data['end'])) {
                        if ($order_data['end'] != $order_data['start']) {
                            $redis->del(getenv('APP_NAME_EN').':lianmaiuser:' . $another_id);
                        }
                    } else {
                        $redis->del(getenv('APP_NAME_EN').':lianmaiuser:' . $another_id);
                    }
                }
                $chat = M('privatechat')->master(true)->where(['order_id' => $orderid])->find();
                if(isset($data['end'])){
                    $status = 0;
                    $error = 1;
                }else{
                    if (isset($data['start'])) {
                        if (!isset($data['end'])) {
                            $data['end'] = $time;
                        }
                    } else {
                        $data['start'] = $time;
                        $data['first_second'] = $randSecond;
                        if(in_array($status, [0,2,3])){
                            $data['end'] = $time;
                        }elseif($checksocket && isset($data['checksocket']) && $data['checksocket'] == 1){
                            $data['checksocket'] = 2;
                        }
                    }

                    if (isset($data['end'])) {
                        $timeL = $data['end'] - $data['start'];
                        if ($timeL >= $data['first_second']) {
                            $order_data['duration'] = $data['duration'] = ceil($timeL / 60);
                            $data['money'] = $data['score'] = $data['duration'] * $data['price'];
                            if ($chat['score']>$data['score']) {
                                $order_data['duration'] = $data['duration'] = ceil($chat['score'] / $data['price']);
                                $data['money'] = $data['score'] = $data['duration'] * $data['price'];
                                if ($timeL % 60 == 0) {
                                    $data['end']++;
                                    $time++;
                                }
                            }
                        }
                    }

                    $data_json = json_encode($data);

                    $orderStatus = M('order_common')->where(['id' => (int)$orderid])->save(['data' => $data_json]);

                    //$chat = M('privatechat')->where(['data' => ['like', '{"orderid":"' . $orderid . '"%']])->find();

                    if ($chat) {
                        $data = json_decode($chat['data'], true);

                        if (isset($data['start'])) {
                            if (!isset($data['end'])) {
                                $data['end'] = ($order_data['duration'] > 0 ? $order_data['duration'] : 1) * 60 + $data['start'] < $time ? ($order_data['duration'] > 0 ? $order_data['duration'] : 1) * 60 + $data['start'] : $time;
                            }
                            if($time - $data['start'] < 30 && $time - $data['start'] > 20 && $user['sex'] == '男'){
                                $newestrecord = M('privatechat_lianmai_records')->master(true)->where(['user_id'=>$another_id, 'type'=>$types])->order('id desc')->find();
                                if($newestrecord && date('Y-m-d', $newestrecord['create_time']) == date('Y-m-d', $time)) {
                                    M('privatechat_lianmai_records')->where(['id'=>$newestrecord['id']])->setInc('num');
                                }else{
                                    M('privatechat_lianmai_records')->add(['user_id'=>$another_id, 'type'=>$types, 'create_time'=>$time, 'num'=>1]);
                                }
                            }
                        } else {
                            $data['start'] = $time;

                            $data['status'] = $status;
                            if(in_array($status, [0,2,3]) && !isset($data['end'])){
                                $data['end'] = $time;
                            }
                        }
                        $data['payer'] = $order['user_id'];
                        if (!isset($data['hpu']) && $status == 0){
                            $data['hpu'] = $touser_id_privacy;
                            if ($status_real == 4) {
                                $data['hpr'] = ($data['hpr'] ?? '').' 远程无可接听的音频';
                            } else if ($status_real == 5) {
                                $data['hpr'] = ($data['hpr'] ?? ''). ' uid:' . $user_id . '离开房间';
                            }
                        }
                        $data_json = json_encode($data, JSON_UNESCAPED_UNICODE);

                        M('privatechat')->where(['id' => $chat['id']])->save(['data' => $data_json]);

                        if (isset($order_data['free_id']) && !S('freechat' . $order_data['free_id']) && ($data['end'] - $data['start']) > 0) {
                            S('freechat' . $order_data['free_id'], '111', 5);
                            $freeKey = ['audio_second', 'video_second'];
                            M('privatechat_free')->where(['id'=>$order_data['free_id']])->setInc($freeKey[$chat['type'] - 9], ($data['end'] - $data['start']));
                        }
                        $chat['data'] = $data_json;

                        (new TencentIM)->modify_c2c_msg($chat['userid'], $chat['touserid'], $data['MsgKey'], json_encode($chat, true));

                        // 更新会话列表
                        D('ChatLists')->changeLists($chat['userid'], $chat['touserid']);
                    }
                }
            }
        } else {
            $orderStatus = true;
        }

        $error = $orderStatus ? false : true;
        $redisInsert = true;
        if(isset($order_data) && isset($order_data['autoinc']) && $order_data['autoinc']){
            if (in_array($status, [0, 2])) {
                $redis->del(getenv('APP_NAME_EN').':lianmai:' . $orderid);
            }else if($status == 1 && $orderid){
                $redisInsert = $redis->set(getenv('APP_NAME_EN').':lianmai:' . $orderid,$orderid,$randSecond);
            }
        }
        if ($status_real == 5) {

        } else if($error || !$redisInsert){
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $another_id, json_encode([
                'code' => 200,
                'action' => 'Home/Privatechat/returnRequest',
                'data' => [
                    'user_id' => $touser_id_privacy,
                    'another_id' => $user_id_privacy,
                    'types' => $types,
                    'channel' => $channel,
                    'name' => $user['name'],
                    'status' => 0
                ]
            ]));
        }else{
            $chatSingle = 0;
            if ($types == 2) {
                $chatSingle = M('privatechat_lianmai_limit')->master(true)->where(['user_id'=>$user_id, 'banned_time'=>['GT', time()]])->find();
                if (!$chatSingle) {
                    $chatSingle = M('privatechat_lianmai_limit_single')->master(true)->where("(user_id=$user_id and touser_id=$another_id) or (user_id=$another_id and touser_id=$user_id)")->where(['banned_time'=>['GT', time()]])->find();
                }
            }
            if (!$chatSingle) {
                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user_id, json_encode([
                    'code' => 200,
                    'action' => 'Home/Privatechat/returnRequest',
                    'data' => [
                        'user_id' => $user_id_privacy,
                        'another_id' => $touser_id_privacy,
                        'types' => $types,
                        'channel' => $channel,
                        'name' => $user['name'],
                        'status' => $status_real
                    ]
                ]));
            }
        }


        
        if (!$status) {
            if($user['sex'] == '女' && !$error){
                $list = M('privatechat')->where(['type'=>['in', [9, 10]], 'userid'=>$user_id_privacy, 'touserid'=>$touser_id_privacy, 'data'=>['like', '%end%']])->order('id desc')->limit(10)->select();

                if(sizeof($list) == 10){
                    $fastdown = 0;
                    foreach ($list as $key => $value) {
                        $tmpdata = json_decode($value['data'], true);
                        if(($tmpdata['end'] - $tmpdata['start'] < 60) && ($tmpdata['end'] - $tmpdata['start'] > 10)){
                            $fastdown += 1;
                        }
                    }
                    if($fastdown == 10){
                        $pushmsg = ["userid" => $user_id_privacy, "touserid" => $touser_id_privacy, "type" => -1, "content" => '系统没问题，检测到对方可能恶意挂断，请谨慎接听', 'finish' => 1, 'single' => 1];
                        M('privatechat')->add($pushmsg);
                        $this->pushNewMsg($pushmsg);
                    }
                }
            }
            /*$order = M('order_common')->where(['id' => $orderid])->find();
            $datas = json_decode($order['data']);

            $free_use = $datas['free_use'] ?: 0;

            if ($free_use) {
                $content = "对方使用免费时长{$free_use}分钟";
                $contain = ["userid" => $another_id, "touserid" => $user_id, "type" => -1, 'single' => 1, "content" => $content, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];

                M('privatechat')->add($contain);
            }*/


            $this->pushNewMsg($chat);
            $this->getOtherList(json_encode(['userid' => $touser_id_privacy, 'count' => '', 'type' => '']));
            // $this->getNewMsg(json_encode(['userid' => $another_id, 'touserid' => $user_id, 'type' => $types + 8]));
            // $this->getNewMsg(json_encode(['userid' => $user_id, 'touserid' => $another_id, 'type' => $types + 8]));

        }/* else if ($status == 1 && $orderid) {
            $this->getcurl(fullPath('api/member/createMic'), 'user_id=' . $order['user_id'] . '&orderid=' . $orderid);
        }*/
        if(in_array($status, ['0','2']) && $order_data['duration'] > 0){
            $LianmaiHistoryMap = $user_id < $another_id ? [
                'user_id' => $user_id,
                'another_id' => $another_id,
            ] :  [
                'user_id' => $another_id,
                'another_id' => $user_id,
            ];
            $ChatChargeRecords = M('chat_charge_records')->master(true)->where($LianmaiHistoryMap)->find();
            // if ($ChatChargeRecords) {
            //     $res = M('chat_charge_records')->where(['id'=>$ChatChargeRecords['id']])->setInc('lianmai_consume', $order_data['money']);
            //     $LianmaiHistoryMap['lianmai_consume'] = $ChatChargeRecords['lianmai_consume'] + $order_data['money'];
            // } else {
            //     $LianmaiHistoryMap['payer'] = $user['sex'] == '女' ? $another_id : $user_id;
            //     $LianmaiHistoryMap['state'] = 0;
            //     $LianmaiHistoryMap['lianmai_consume'] = $order_data['money'];
            //     $LianmaiHistoryMap['time'] = $time;
            //     M('chat_charge_records')->add($LianmaiHistoryMap);
            // }
            if ($ChatChargeRecords && $LianmaiHistoryMap['lianmai_consume'] > 2500) {
                $pushmsg = $another_id == $ChatChargeRecords['payer'] ? ["userid" => $user_id, "touserid" => $another_id, "type" => -1, "content" => '本平台无解锁功能，请谨慎消费', 'finish' => 1, 'single' => 1] : ["userid" => $another_id, "touserid" => $user_id, "type" => -1, "content" => '本平台无解锁功能，请谨慎消费', 'finish' => 1, 'single' => 1];
                M('privatechat')->add($pushmsg);
                $this->pushNewMsg($pushmsg);
            }
        }

        exit(json_encode(['code' => 200, 'msg' => '']));
    }
    
      // 语音通话请求结果
    public function returnRequest()
    {
        $user_id = I('user_id');
        $another_id = I('another_id');
        $channel = I('channel');        // 加入的频道
        $status_real = $status = I('status');          // 0取消 | 1接听 | 2无权限 | 4无音频前端取消 | 5通话断开
        $types = I('types');            // 1语音 | 2视频
        $orderid = I('orderid');
        $checksocket = I('auto', 0);
        $error = 0;

        if (in_array($status_real, ['4', '5'])) {
            $status = 0;
        }

        $configs = M('config_system')->master(true)->where(['category'=>'chat'])->getField('title,content');
        $f_start = $configs['lianmai_first_start'] ?? 17;
        $f_end = $configs['lianmai_first_end'] ?? 25;
        if ($f_start >= 56 || $f_start < 5) $f_start = 17;
        if ($f_end >= 56 || $f_end < 5) $f_end = 25;
         $randSecond = rand($f_start,$f_end);
        //   $randSecond = rand(1,2);
        // $randSecond = 29;

        $user_privacy = $user = M('user')->where(['id' => $user_id])->find();
        $user_id_privacy = $user_id;
        $touser_id_privacy = $another_id;
        if ($user['reg']==2) {
            $user = M('user')->where(['id' => $user_privacy['authcode']])->find();
            $user_id = $user['id'];
            $another_id = M('user')->where(['id' => $touser_id_privacy])->getField('authcode');
        }
        $redis = new \Redis();
        $redis->connect('127.0.0.1',getenv('REDIS_PORT'));
        if(getenv('REDIS_PASS')){
            $redis->auth(getenv('REDIS_PASS'));
        }
        $time = time();
        if ($orderid) {
            $order = M('order_common')->master(true)->find($orderid);

            if ($order) {
                $order_data = $data = json_decode($order['data'], true);
                if ($order_data && in_array($status, [0, 2]) && isset($order_data['start'])) {
                    if (isset($order_data['end'])) {
                        if ($order_data['end'] != $order_data['start']) {
                            $redis->del(getenv('APP_NAME_EN').':lianmaiuser:' . $another_id);
                        }
                    } else {
                        $redis->del(getenv('APP_NAME_EN').':lianmaiuser:' . $another_id);
                    }
                }
                $chat = M('privatechat')->master(true)->where(['order_id' => $orderid])->find();
                if(isset($data['end'])){
                    $status = 0;
                    $error = 1;
                }else{
                    if (isset($data['start'])) {
                        if (!isset($data['end'])) {
                            $data['end'] = $time;
                        }
                    } else {
                        $data['start'] = $time;
                        $data['first_second'] = $randSecond;
                        if(in_array($status, [0,2,3])){
                            $data['end'] = $time;
                        }elseif($checksocket && isset($data['checksocket']) && $data['checksocket'] == 1){
                            $data['checksocket'] = 2;
                        }
                    }

                    if (isset($data['end'])) {
                        $timeL = $data['end'] - $data['start'];
                        if ($timeL >= $data['first_second']) {
                            $order_data['duration'] = $data['duration'] = ceil($timeL / 60);
                            $data['money'] = $data['score'] = $data['duration'] * $data['price'];
                            if ($chat['score']>$data['score']) {
                                $order_data['duration'] = $data['duration'] = ceil($chat['score'] / $data['price']);
                                $data['money'] = $data['score'] = $data['duration'] * $data['price'];
                                if ($timeL % 60 == 0) {
                                    $data['end']++;
                                    $time++;
                                }
                            }
                        }
                    }

                    $data_json = json_encode($data);

                    $orderStatus = M('order_common')->where(['id' => (int)$orderid])->save(['data' => $data_json]);

                    //$chat = M('privatechat')->where(['data' => ['like', '{"orderid":"' . $orderid . '"%']])->find();

                    if ($chat) {
                        $data = json_decode($chat['data'], true);

                        if (isset($data['start'])) {
                            if (!isset($data['end'])) {
                                $data['end'] = ($order_data['duration'] > 0 ? $order_data['duration'] : 1) * 60 + $data['start'] < $time ? ($order_data['duration'] > 0 ? $order_data['duration'] : 1) * 60 + $data['start'] : $time;
                            }
                            if($time - $data['start'] < 30 && $time - $data['start'] > 20 && $user['sex'] == '男'){
                                $newestrecord = M('privatechat_lianmai_records')->master(true)->where(['user_id'=>$another_id, 'type'=>$types])->order('id desc')->find();
                                if($newestrecord && date('Y-m-d', $newestrecord['create_time']) == date('Y-m-d', $time)) {
                                    M('privatechat_lianmai_records')->where(['id'=>$newestrecord['id']])->setInc('num');
                                }else{
                                    M('privatechat_lianmai_records')->add(['user_id'=>$another_id, 'type'=>$types, 'create_time'=>$time, 'num'=>1]);
                                }
                            }
                        } else {
                            $data['start'] = $time;

                            $data['status'] = $status;
                            if(in_array($status, [0,2,3]) && !isset($data['end'])){
                                $data['end'] = $time;
                            }
                        }
                        $data['payer'] = $order['user_id'];
                        if (!isset($data['hpu']) && $status == 0){
                            $data['hpu'] = $touser_id_privacy;
                            if ($status_real == 4) {
                                $data['hpr'] = ($data['hpr'] ?? '').' 远程无可接听的音频';
                            } else if ($status_real == 5) {
                                $data['hpr'] = ($data['hpr'] ?? ''). ' uid:' . $user_id . '离开房间';
                            }
                        }
                        $data_json = json_encode($data, JSON_UNESCAPED_UNICODE);

                        M('privatechat')->where(['id' => $chat['id']])->save(['data' => $data_json]);

                        if (isset($order_data['free_id']) && !S('freechat' . $order_data['free_id']) && ($data['end'] - $data['start']) > 0) {
                            S('freechat' . $order_data['free_id'], '111', 5);
                            $freeKey = ['audio_second', 'video_second'];
                            M('privatechat_free')->where(['id'=>$order_data['free_id']])->setInc($freeKey[$chat['type'] - 9], ($data['end'] - $data['start']));
                        }
                        $chat['data'] = $data_json;

                        (new TencentIM)->modify_c2c_msg($chat['userid'], $chat['touserid'], $data['MsgKey'], json_encode($chat, true));

                        // 更新会话列表
                        D('ChatLists')->changeLists($chat['userid'], $chat['touserid']);
                    }
                }
            }
        } else {
            $orderStatus = true;
        }

        $error = $orderStatus ? false : true;
        $redisInsert = true;
        if(isset($order_data) && isset($order_data['autoinc']) && $order_data['autoinc']){
            if (in_array($status, [0, 2])) {
                $redis->del(getenv('APP_NAME_EN').':lianmai:' . $orderid);
            }else if($status == 1 && $orderid){
                $redisInsert = $redis->set(getenv('APP_NAME_EN').':lianmai:' . $orderid,$orderid,$randSecond);
            }
        }
        if ($status_real == 5) {

        } else if($error || !$redisInsert){
            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $another_id, json_encode([
                'code' => 200,
                'action' => 'Home/Privatechat/returnRequest',
                'data' => [
                    'user_id' => $touser_id_privacy,
                    'another_id' => $user_id_privacy,
                    'types' => $types,
                    'channel' => $channel,
                    'name' => $user['name'],
                    'status' => 0
                ]
            ]));
        }else{
            $chatSingle = 0;
            if ($types == 2) {
                $chatSingle = M('privatechat_lianmai_limit')->master(true)->where(['user_id'=>$user_id, 'banned_time'=>['GT', time()]])->find();
                if (!$chatSingle) {
                    $chatSingle = M('privatechat_lianmai_limit_single')->master(true)->where("(user_id=$user_id and touser_id=$another_id) or (user_id=$another_id and touser_id=$user_id)")->where(['banned_time'=>['GT', time()]])->find();
                }
            }
            if (!$chatSingle) {
                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user_id, json_encode([
                    'code' => 200,
                    'action' => 'Home/Privatechat/returnRequest',
                    'data' => [
                        'user_id' => $user_id_privacy,
                        'another_id' => $touser_id_privacy,
                        'types' => $types,
                        'channel' => $channel,
                        'name' => $user['name'],
                        'status' => $status_real
                    ]
                ]));
            }
        }


        
        if (!$status) {
            if($user['sex'] == '女' && !$error){
                $list = M('privatechat')->where(['type'=>['in', [9, 10]], 'userid'=>$user_id_privacy, 'touserid'=>$touser_id_privacy, 'data'=>['like', '%end%']])->order('id desc')->limit(10)->select();

                if(sizeof($list) == 10){
                    $fastdown = 0;
                    foreach ($list as $key => $value) {
                        $tmpdata = json_decode($value['data'], true);
                        if(($tmpdata['end'] - $tmpdata['start'] < 60) && ($tmpdata['end'] - $tmpdata['start'] > 10)){
                            $fastdown += 1;
                        }
                    }
                    if($fastdown == 10){
                        $pushmsg = ["userid" => $user_id_privacy, "touserid" => $touser_id_privacy, "type" => -1, "content" => '系统没问题，检测到对方可能恶意挂断，请谨慎接听', 'finish' => 1, 'single' => 1];
                        M('privatechat')->add($pushmsg);
                        $this->pushNewMsg($pushmsg);
                    }
                }
            }
            /*$order = M('order_common')->where(['id' => $orderid])->find();
            $datas = json_decode($order['data']);

            $free_use = $datas['free_use'] ?: 0;

            if ($free_use) {
                $content = "对方使用免费时长{$free_use}分钟";
                $contain = ["userid" => $another_id, "touserid" => $user_id, "type" => -1, 'single' => 1, "content" => $content, 'isRead' => 1, 'sound_tip' => 1, 'finish' => 1];

                M('privatechat')->add($contain);
            }*/


            $this->pushNewMsg($chat);
            $this->getOtherList(json_encode(['userid' => $touser_id_privacy, 'count' => '', 'type' => '']));
            // $this->getNewMsg(json_encode(['userid' => $another_id, 'touserid' => $user_id, 'type' => $types + 8]));
            // $this->getNewMsg(json_encode(['userid' => $user_id, 'touserid' => $another_id, 'type' => $types + 8]));

        }/* else if ($status == 1 && $orderid) {
            $this->getcurl(fullPath('api/member/createMic'), 'user_id=' . $order['user_id'] . '&orderid=' . $orderid);
        }*/
        if(in_array($status, ['0','2']) && $order_data['duration'] > 0){
            $LianmaiHistoryMap = $user_id < $another_id ? [
                'user_id' => $user_id,
                'another_id' => $another_id,
            ] :  [
                'user_id' => $another_id,
                'another_id' => $user_id,
            ];
            $ChatChargeRecords = M('chat_charge_records')->master(true)->where($LianmaiHistoryMap)->find();
            // if ($ChatChargeRecords) {
            //     $res = M('chat_charge_records')->where(['id'=>$ChatChargeRecords['id']])->setInc('lianmai_consume', $order_data['money']);
            //     $LianmaiHistoryMap['lianmai_consume'] = $ChatChargeRecords['lianmai_consume'] + $order_data['money'];
            // } else {
            //     $LianmaiHistoryMap['payer'] = $user['sex'] == '女' ? $another_id : $user_id;
            //     $LianmaiHistoryMap['state'] = 0;
            //     $LianmaiHistoryMap['lianmai_consume'] = $order_data['money'];
            //     $LianmaiHistoryMap['time'] = $time;
            //     M('chat_charge_records')->add($LianmaiHistoryMap);
            // }
            if ($ChatChargeRecords && $LianmaiHistoryMap['lianmai_consume'] > 2500) {
                $pushmsg = $another_id == $ChatChargeRecords['payer'] ? ["userid" => $user_id, "touserid" => $another_id, "type" => -1, "content" => '本平台无解锁功能，请谨慎消费', 'finish' => 1, 'single' => 1] : ["userid" => $another_id, "touserid" => $user_id, "type" => -1, "content" => '本平台无解锁功能，请谨慎消费', 'finish' => 1, 'single' => 1];
                M('privatechat')->add($pushmsg);
                $this->pushNewMsg($pushmsg);
            }
        }

        exit(json_encode(['code' => 200, 'msg' => '']));
    }


    //-----------------------------------------------------------------

    // 聊天图片焚毁
    public function burnImg()
    {
        $id = I('id');
        $user_id = I('user_id');   // 发送者id
        $touserid = I('touserid'); // 接受者id

        $result = M('privatechat')->where(['id' => $id, 'touserid' => $touserid, 'type' => 1])->setField('is_burn', -1);

        if ($result) {
            $message = json_encode(['code' => 200, 'action' => 'Home/Privatechat/burnImg', 'msg' => '焚毁成功', 'data' => ['id' => $id]]);

            Gateway::sendToUid([getenv('SOCKET_PREFIX') . $user_id, getenv('SOCKET_PREFIX') . $touserid], $message);   // 实时显示图片是否已焚毁
        } else {
            $message = json_encode(['code' => 400, 'action' => 'Home/Privatechat/burnImg', 'msg' => '焚毁失败']);

            Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user_id, $message);   // 实时显示图片是否已焚毁
        }
    }

    //-----------------------------------------------------------------

    public function allRead()
    {
        $user_id = I('user_id');

        M('privatechat')->where(['touserid' => $user_id, 'isRead' => 0])->save(['isRead' => 1, 'sound_tip' => 1]);

        exit(json_encode(['code' => 200, 'msg' => '设置成功']));
    }

    // 置顶聊天
    public function topChat()
    {
        $types = I('types'); // 1私聊|2群聊
        $uid = I('uid');
        $touid = I('touid');

        $where = ['types' => $types, 'uid' => $uid, 'to_uid' => $touid];

        if (!$touid || !$uid) {
            exit(json_encode(['code' => 400, 'result' => '缺少参数']));
        }
        $res = M('top_chat')->where($where)->find();

        if ($res) {
            M('top_chat')->where($where)->delete();

            $is_top = 0;
        } else {
            M('top_chat')->add($where);

            $is_top = 1;
        }

        // 更新会话列表
        D('ChatLists')->changeLists($uid, $touid, 'top', $is_top);

        (new TencentIM)->top($uid, $touid, $is_top ?: 2);

        exit(json_encode(['code' => 200, 'msg' => '成功']));
    }

    public function forward()
    {
        $chat_id = intval(I('chat_id'));
        $user_id = intval(I('user_id'));
        $to_user = intval(I('to_user'));

        if (!$user_id || !$to_user) {
            exit(json_encode(['code' => 400, 'msg' => '操作失败']));
        }

        if ($user_id == $to_user) {
            exit(json_encode(['code' => 400, 'msg' => '无法转发给自己']));
        }

        $chat = M('privatechat')->where(['id' => $chat_id])->find();

        if (!$chat) {
            exit(json_encode(['code' => 400, 'msg' => '消息不存在']));
        }

        if ($chat['userid'] != $user_id && $chat['touserid'] != $user_id) {
            exit(json_encode(['code' => 400, 'msg' => '操作失败']));
        }

        $response = $this->addTalk($user_id, $to_user, $chat['type'], $chat['content'], $chat['second']);

        if ($response) {
            return $response;
        } else {
            exit(json_encode(['code' => 200, 'msg' => '转发成功']));
        }
    }

    //----------------------------------------------------
    
    public function greet()
    {
        exit;

        $config = M('config_system')->where(['category' => ['in', ['greet', 'kefu']]])->getField('title, content');
        
        $kefu = intval($config['id']);
        
        if ($config['greet_newest']) {
            $space = $config['greet_newest'] + 60 * $config['greet_space'];
            if ($space > time()) {
                exit;
            }
        }
        
        if ($config['greet_switch'] + 0) {
            M('config_system')->where(['title' => 'greet_newest'])->save(['content' => time()]);
            
            $now = date('H');
            
            if ($config['greet_start'] <= $now && $now < $config['greet_end']) {
                
                // 女性向男性打招呼
                // 男性
                $where = $whereOr = [
                    //'id' => ['neq', $kefu],
                    'id' => ['gt', '5555555'],
                    'sex' => '男',
                    'role' => 0,
                    'is_banned' => 0,
                    'proxy' => 0,
                    'greet_receive_count' => ['lt', $config['greet_male_receive_max']],
                    'yqr' => ['eq', '']
                ];
                
                $where['is_online'] = 1;
                $last_login_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d')));
                $where['last_login_datetime'] = ['gt', $last_login_date];
                $whereOr['is_online'] = 0;
                
                //$whereOr['last_login_datetime'] = ['gt', date('Y-m-d H:i:s', strtotime('-1 day'))];
                $whereOr['last_login_datetime'] = ['gt', date('Y-m-d H:i:s', (time() - 14400))];
                
                $males = M('user')->where($where)->order('tycoon desc, volley desc, noble_grade desc')->select();
                
                if ($males) {
                    $contents = M('privatechat_zhaohu')->where(['types' => 2, 'is_hidden' => 0])->cache(86400)->getField('content', true);
                    
                    if ($contents) {
                        $males_ids = array_column($males, 'id');
                        
                        $where = [
                            //'id' => ['neq', $kefu],
                            'id' => ['gt', '5555555'],
                            'sex' => '女',
                            'is_banned' => 0,
                            'is_identity_authentication' => 2,
                            'proxy' => 0,
                            'greet_count' => ['lt', $config['greet_female_max']]
                        ];
                        /*if (!$config['greet_offline']) {
                            $where['last_login_datetime'] = ['gt', date('Y-m-d H:i:s', strtotime('-2 day'))];
                        }*/
                        
                        $females = M('user')->field('id, voice, voice_time, greet_count, greet_time')->where($where)->order('role asc, is_online desc, charm_value desc, shouyi desc, following desc, zan desc, proxy desc')->select();
                        
                        if ($females) {
                            $start = strtotime(date('Ymd')) - 86400 * 4;
                            $greetRecords = M('greet_records')->where(['user_id' => ['in', $males_ids], 'create_time' => ['gt', $start]])->select();
                            
                            $greetContain = [];
                            foreach ($greetRecords as $key => $item) {
                                $greetContain[] = $item['user_id'] . '+' . $item['to_user'];
                            }
                            
                            $females_ids = array_column($females, 'id');
                            $userImgs = M('user_img')->where(['types' => 1, 'user_id' => ['in', $females_ids], 'packet' => 0, 'is_auth' => 0, 'is_avatar' => 0, 'status' => 1])->order('rand()')->getField('user_id, picthumb');
                            //$userDymanics = M('dymanic')->where(['type' => 0, 'userid' => ['in', $females_ids], 'shenhe' => 1])->getField('userid, dy_id, content, sumbImage,video, cover');
                            $userDymanics = [];
                            $start_time = strtotime(date('Y-m-d'));
                            $end_time = $start_time + 86399;
                            $greet_count_day = M('greet_records')->where(['user_id' => ['in', $males_ids], 'create_time' => ['between', [$start_time, $end_time]]])->group('user_id')->getField('user_id, count(*) count');
                            
                            $insert = [];
                            $update_male = [];
                            $update_female = [];
                            $current_time = time();
                            $greet_offline_max = explode(',', $config['greet_offline_max']);
                            foreach ($males as $key => $item) {
                                if ($item['id'] != $kefu) {
                                    if (!$item['is_online'] && isset($greet_count_day[$item['id']]) && $greet_count_day[$item['id']] >= $greet_offline_max[0]) {
                                        continue;
                                    } else {
                                        $push_count = 0;
                                        foreach ($females as $m => $n) {
                                            if ($n['id'] == $kefu) {
                                                continue;
                                            }

                                            if ($push_count < $config['greet_female_count']) {
                                                if ($n['greet_count'] < $config['greet_female_max']) {
                                                    $merge = $item['id'] . '+' . $n['id'];
                                                    if (!in_array($merge, $greetContain)) {
                                                        $greetContain[] = $merge;
                                                        $insert[] = ['user_id' => $item['id'], 'to_user' => $n['id'], 'create_time' => $current_time];

                                                        //M('greet_records')->add(['user_id' => $item['id'], 'to_user' => $n['id'], 'create_time' => $current_time]);

                                                        $females[$m]['greet_count'] = $n['greet_count'] = $n['greet_count'] + 1;

                                                        if (isset($update_female[$n['id']])) {
                                                            $update_female[$n['id']]['greet_count'] = $n['greet_count'];
                                                            $update_female[$n['id']]['greet_time'] = $current_time;
                                                        } else {
                                                            $update_female[$n['id']] = ['id' => $n['id'], 'greet_count' => $n['greet_count'], 'greet_time' => $current_time];
                                                        }

                                                        $item['greet_receive_count'] += 1;
                                                        if (isset($update_male[$item['id']])) {
                                                            $update_male[$item['id']]['greet_receive_count'] = $item['greet_receive_count'];
                                                            $update_male[$item['id']]['greet_receive_time'] = $current_time;
                                                        } else {
                                                            $update_male[$item['id']] = ['id' => $item['id'], 'greet_receive_count' => $item['greet_receive_count'], 'greet_receive_time' => $current_time];
                                                        }

                                                        $push_count += 1;

                                                        $rand = mt_rand(0, count($contents) - 1);
                                                        $content = $contents[$rand];
                                                        $chat_type = 0;
                                                        $chat_second = 0;
                                                        $chat_datas = '';

                                                        $chat_contain = ['0', '1', '2', '11'];

                                                        //$chat_rand = mt_rand(0, 2);
                                                        $chat_rand = 0;
                                                        if ($chat_contain[$chat_rand] == 1) {
                                                            if (isset($userImgs[$n['id']])) {
                                                                $userImg = json_decode($userImgs[$n['id']], true);

                                                                if (isset($userImg[0])) {
                                                                    $chat_type = 1;
                                                                    $content = $userImg[0];
                                                                }
                                                            }
                                                        } else if ($chat_contain[$chat_rand] == 2) {
                                                            if ($n['voice']) {
                                                                $chat_type = 2;
                                                                $content = $n['voice'];
                                                                $chat_second = $n['voice_time'];
                                                            }
                                                        } else if ($chat_contain[$chat_rand] == 11) {
                                                            if (isset($userDymanics[$n['id']])) {
                                                                $chat_type = 11;
                                                                $content = '[动态]';

                                                                $chat_datas = [
                                                                    'dy_id' => $userDymanics[$n['id']]['dy_id'],
                                                                    'content' => $userDymanics[$n['id']]['content'],
                                                                ];

                                                                if ($userDymanics[$n['id']]['video']) {
                                                                    $chat_datas['video'] = $userDymanics[$n['id']]['video'];
                                                                    $chat_datas['cover'] = $userDymanics[$n['id']]['cover'];
                                                                } else {
                                                                    $chat_datas['images'] = $userDymanics[$n['id']]['sumbImage'];
                                                                }

                                                                $chat_datas = json_encode($chat_datas, JSON_UNESCAPED_UNICODE);
                                                            }
                                                        }

                                                        $data = [
                                                            'userid' => $n['id'],
                                                            'touserid' => $item['id'],
                                                            'type' => $chat_type,
                                                            'content' => $content,
                                                            'second' => $chat_second,
                                                            'data' => $chat_datas,
                                                            'timing' => 1,
                                                            'greet' => 1,
                                                            'system_greet' => 1,
                                                        ];

                                                        usleep(5000);

                                                        $this->addTalk($n['id'], $item['id'], $chat_type, $content, $chat_second, $chat_datas, 1, 1, 1);
                                                    }
                                                }
                                            } else {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            
                            if ($insert) {
                                $GreetRecords = M("greet_records");
                                $GreetRecords->addAll($insert);
                            }
                            
                            
                            if ($update_female) {
                                $User = M("User");
                                foreach ($update_female as $key => $item) {
                                    $User->save($item);
                                }
                            }
                            
                            if ($update_male) {
                                $User = M("User");
                                foreach ($update_male as $key => $item) {
                                    $User->save($item);
                                }
                            }
                        }
                    }
                }
                
                sleep(3);
                
                // 男性向女性打招呼
                // 女性
                $where = $whereOr = [
                    //'id' => ['neq', $kefu],
                    'id' => ['gt', '5555555'],
                    'sex' => '女',
                    'role' => 0,
                    'is_banned' => 0,
                    'is_identity_authentication' => 2,
                    'proxy' => 0,
                    'greet_receive_count' => ['lt', $config['greet_female_receive_max']]
                ];
                
                $where['is_online'] = 1;
                $last_login_date = date('Y-m-d H:i:s', strtotime(date('Y-m-d')));
                $where['last_login_datetime'] = ['gt', $last_login_date];
                $whereOr['is_online'] = 0;
                //$whereOr['last_login_datetime'] = ['gt', date('Y-m-d H:i:s', strtotime('-1 day'))];
                $whereOr['last_login_datetime'] = ['gt', date('Y-m-d H:i:s', (time() - 14400))];
                
                $females = M('user')->where($where)->order('score desc, following desc, zan desc, charm_value desc')->select();
                
                if ($females) {
                    $contents = M('privatechat_zhaohu')->where(['types' => 1, 'is_hidden' => 0])->cache(86400)->getField('content', true);
                    
                    if ($contents) {
                        $females_ids = array_column($females, 'id');
                        
                        $where = [
                            //'id' => ['neq', $kefu],
                            'id' => ['gt', '5555555'],
                            'sex' => '男',
                            'is_banned' => 0,
                            'proxy' => 0,
                            'greet_count' => ['lt', $config['greet_male_max']],
                            'yqr' => ['eq', '']
                        ];
                        
                        /*if (!$config['greet_offline']) {
                            $where['last_login_datetime'] = ['gt', date('Y-m-d H:i:s', strtotime('-2 day'))];
                        }*/
                        
                        $males = M('user')->where($where)->order('is_online desc, noble_grade desc, volley desc, tycoon desc')->select();
                        
                        if ($males) {
                            
                            $start = strtotime(date('Ymd')) - 86400 * 5;
                            $greetRecords = M('greet_records')->where(['user_id' => ['in', $females_ids], 'create_time' => ['gt', $start]])->select();
                            
                            $greetContain = [];
                            foreach ($greetRecords as $key => $item) {
                                $greetContain[] = $item['user_id'] . '+' . $item['to_user'];
                            }
                            
                            $start_time = strtotime(date('Y-m-d'));
                            $end_time = $start_time + 86399;
                            $greet_count_day = M('greet_records')->where(['user_id' => ['in', $females_ids], 'create_time' => ['between', [$start_time, $end_time]]])->group('user_id')->getField('user_id, count(*) count');
                            
                            $insert = [];
                            $update_male = [];
                            $update_female = [];
                            $current_time = time();
                            $greet_offline_max = explode(',', $config['greet_offline_max']);
                            foreach ($females as $key => $item) {
                                if ($item['id'] != $kefu) {
                                    if (!$item['is_online'] && isset($greet_count_day[$item['id']]) && $greet_count_day[$item['id']] >= $greet_offline_max[0]) {
                                        continue;
                                    } else {
                                        $push_count = 0;
                                        foreach ($males as $m => $n) {
                                            if ($n['id'] == $kefu) {
                                                continue;
                                            }

                                            if ($push_count < $config['greet_male_count']) {
                                                if ($n['greet_count'] < $config['greet_male_max']) {
                                                    $merge = $item['id'] . '+' . $n['id'];
                                                    if (!in_array($merge, $greetContain)) {
                                                        $greetContain[] = $merge;
                                                        $insert[] = ['user_id' => $item['id'], 'to_user' => $n['id'], 'create_time' => $current_time];

                                                        //M('greet_records')->add(['user_id' => $item['id'], 'to_user' => $n['id'], 'create_time' => $current_time]);

                                                        $males[$m]['greet_count'] = $n['greet_count'] = $n['greet_count'] + 1;

                                                        if (isset($update_male[$n['id']])) {
                                                            $update_male[$n['id']]['greet_count'] = $n['greet_count'];
                                                            $update_male[$n['id']]['greet_time'] = $current_time;
                                                        } else {
                                                            $update_male[$n['id']] = ['id' => $n['id'], 'greet_count' => $n['greet_count'], 'greet_time' => $current_time];
                                                        }

                                                        $item['greet_receive_count'] += 1;
                                                        if (isset($update_female[$item['id']])) {
                                                            $update_female[$item['id']]['greet_receive_count'] = $item['greet_receive_count'];
                                                            $update_female[$item['id']]['greet_receive_time'] = $current_time;
                                                        } else {
                                                            $update_female[$item['id']] = ['id' => $item['id'], 'greet_receive_count' => $item['greet_receive_count'], 'greet_receive_time' => $current_time];
                                                        }

                                                        $push_count += 1;

                                                        $rand = mt_rand(0, count($contents) - 1);

                                                        $data = [
                                                            'userid' => $n['id'],
                                                            'touserid' => $item['id'],
                                                            'content' => $contents[$rand],
                                                            'timing' => 1,
                                                            'greet' => 1,
                                                            'system_greet' => 1,
                                                        ];

                                                        usleep(5000);

                                                        $this->addTalk($n['id'], $item['id'], 0, $content, 0, '', 1, 1, 1);
                                                    }
                                                }
                                            } else {
                                                break;
                                            }
                                        }
                                    }
                                }
                            }
                            
                            if ($insert) {
                                $GreetRecords = M("greet_records");
                                $GreetRecords->addAll($insert);
                            }
                            
                            if ($update_male) {
                                $User = M("User");
                                foreach ($update_male as $key => $item) {
                                    $User->save($item);
                                }
                            }
                            
                            if ($update_female) {
                                $User = M("User");
                                foreach ($update_female as $key => $item) {
                                    $User->save($item);
                                }
                            }
                        }
                    }
                }
            }
        }
    }

    public function loginGreet($user_id)
    {
        exit;

        $config = M('config_system')->where(['category' => ['in', ['kefu']]])->getField('title, content');
    
        $kefu = intval($config['id']);
        
        if ($kefu != $user_id) {
            $user = M('user')->field('id, sex, is_online, last_login_datetime, yqr')->where(['id' => $user_id])->find();
    
            if ($user['sex'] == '男' && $user['yqr']) {
                exit;
            }
            
            if ($user['is_online'] && (strtotime($user['last_login_datetime']) + 10) > time()) {
                $kefu = M('config_system')->where(['title' => 'id'])->getField('content');
                $kefu = intval($kefu);
        
                $sex = $user['sex'] == '男' ? '女' : '男';
                $where = ['id' => ['neq', $kefu], 'sex' => $sex, 'is_online' => 1];
    
                if ($user['sex'] == '女') {
                    $where['yqr'] = ['eq', ''];
                }
        
                $count = mt_rand(20, 30);
        
                $ids = M('user')->where($where)->order('rand()')->limit($count)->getField('id', true);
        
                $types = $user['sex'] == '男' ? 2 : 1;
        
                $contents = M('privatechat_zhaohu')->where(['types' => $types, 'is_hidden' => 0])->getField('content', true);
        
                if ($contents) {
                    foreach ($ids as $item) {
                        $contentsCount = count($contents) - 1;
                        $content = $contents[mt_rand(0, $contentsCount)];
                
                        $this->addTalk($item, $user_id, 0, $content, 0, '', 1, 0, 1, 1);
                    }
                }
            }
        }
    }

    // 今日缘分
    public function fatebak($id, $user_id)
    {
        $ids = explode(',', $id);
        
        $user = M('user')->field('id, sex')->where(['id' => $user_id])->find();
        $types = $user['sex'] == '男' ? 1 : 2;
        
        $contents = M('privatechat_default')->where(['types' => $types, 'channel' => 2, 'user_id' => ['in', [0, $user_id]]])->getField('content', true);
        if (!$contents) {
            $contents = M('privatechat_zhaohu')->where(['types' => $types, 'is_hidden' => 0])->getField('content', true);
        }

        M('user')->where(['id' => $user_id])->setField('zhaohu_time', time());
        
        if ($contents) {
            // 心动数+1
            M('user')->where(['id' => ['in', $ids]])->setInc('heart');
            
            foreach ($ids as $item) {
                $content = $contents[mt_rand(0, count($contents) - 1)];
                $this->addTalk($user_id, $item, 0, $content, 0, '', 1, 0, 0, 0, 0, 1);
            }
        }
    }



    public function fate($id, $user_id, $word_id='', $window=0, $return = 0, $front_id = '', $userid = 0)
    {
        $ids = explode(',', $id);

        // if(sizeof($ids) == 1){
        //     $fields = $user_id < $id ? 'couple_a' : 'couple_b';
        //     $intimate = M('user_intimate')->where([$fields=>$user_id.','.$id])->getField('intimate');
        //     if($intimate && $intimate>0){
        //         exit(json_encode(['code'=>400, 'msg'=>'你们已经有亲密度了，不能向对方打招呼']));
        //     }
        // }
        if ($userid) {
            $user_id = $userid;
        }
        $is_public = 0;
        $user_privacy = $user = M('user')->field('id, sex, yqr, yqm, realname_auth,is_identity_authentication,register_datetime, entertainment, noble_grade, noble_time, reg, authcode')->where(['id' => $user_id])->find();
        if ($user['reg'] == 2) {
            $user = M('user')->field('id, sex, yqr, yqm, realname_auth,is_identity_authentication,register_datetime, entertainment, noble_grade, noble_time, reg, authcode')->where(['id' => $user_privacy['authcode']])->find();
        }
        if($window == 0){
            $result = D('Privatechat')->checkGreet($user['id']);
            if ($result && $result['code'] == 400) {
                exit(json_encode($result));
            }
            $fateForbatch = S('fateForbatch:' . $user['id']);
            if($fateForbatch){
                exit(json_encode(['code'=>400, 'msg'=>'请勿重复点击']));
            }
            S('fateForbatch:' . $user['id'], 1, 10);
        }else{
            $fateForWindow = S('fateForWindow:' . $user['id'] . ':' . $id);
            $fateForWindow = $fateForWindow ? $fateForWindow : 0;
            if($fateForWindow > 2){
                exit(json_encode(['code'=>400, 'msg'=>'发送频繁']));
            }
            $fateForWindow++;
            S('fateForWindow:' . $user['id'] . ':' . $id, $fateForWindow, 60);

            if (!($user['entertainment'] == 0 && $user['sex'] == '女')) {
                $sayhiNum = 10;
                if ($user['noble_grade'] && $user['noble_time'] > $current_time) {
                    $privilege = M('grade_noble')->where(['grade' => $user['noble_grade']])->getField('privilege');
                    $privilege = explode(',', $privilege);
                    if (in_array(17, $privilege)) {
                        $sayhiNum = 50;
                    }
                }
                $is_public = 1;
                $fates = M('privatechat')->where(['userid'=>$user['id'], 'is_fate'=>1, 'is_public'=>1, 'front_id'=>['gt', 0], 'addtime'=>['egt', date('Y-m-d') . ' 00:00:00']])->getField('touserid', true);
                if (sizeof($fates) >= $sayhiNum) {
                    exit(json_encode(['code'=>400, 'msg'=>'今日打招呼次数已达上限']));
                }
            } else {
                $fates = M('privatechat')->where(['userid'=>$user['id'], 'is_fate'=>1, 'front_id'=>['gt', 0], 'addtime'=>['egt', date('Y-m-d') . ' 00:00:00']])->getField('touserid', true);

                switch (intval($user['quality'])) {
                    case 0:
                    case 1:
                    case 2:
                        $sayhiCount = 50;
                        break;
                    case 3:
                        $sayhiCount = 100;
                        break;
                    
                    default:
                        $sayhiCount = 150;
                        break;
                }

                if (sizeof($fates) >= $sayhiCount) {
                    exit(json_encode(['code'=>400, 'msg'=>'今日打招呼次数已达上限']));
                }
            }
        }

        $seeRecord = M('see_record');

        
        if ($ids) {
            if ($word_id) {
                $word_ids = explode(',', $word_id);

                $reCheck = 1;
                if ($window && $user['sex'] == '女' && !in_array($user['realname_auth'], [1,2]) && $user['entertainment'] != 1) {
                    $userData = M('user_data')->where(['user_id'=>$id])->find();
                    if($userData && $userData['topup'] > 0) {
                        exit(json_encode(['code' => 400, 'msg' => '未实名认证']));
                    }
                    $reCheck = 0;
                }
                if($reCheck && $user['sex'] == '女' && $user['realname_auth'] != 2){
                    if (strtotime('2023-06-01') > strtotime($user['register_datetime'])) {
                        exit(json_encode(['code' => 400, 'msg' => '未实名认证']));
                    } else if ($user['is_identity_authentication'] != 2) {
                        exit(json_encode(['code' => 400, 'msg' => '未真人认证']));
                    } else if ($user['realname_auth'] != 1) {
                        $hasAuthIdCard = M('user_certification')->where(['types'=>1, 'user_id'=>$user['id']])->find();
                        if (!$hasAuthIdCard || $hasAuthIdCard['status'] == -1) {
                            exit(json_encode(['code' => 400, 'msg' => '未实名认证']));
                        }
                    }
                }
                $types = $user['sex'] == '男' ? 1 : 2;

                $words = M('privatechat_greet')->where(['id' => ['in', $word_id], 'user_id' => $user['id'], 'status' => 1])->getField('id, channel, content, voice_time');

                M('user')->where(['id' => $user['id']])->setField('zhaohu_time', time());

                $touser = M('user')->where(['id' => ['in', $ids]])->getField('id, sex, yqr, yqm, authcode');
                if ($user_privacy['reg'] == 2) {
                    $touser_real = M('user')->where(['id' => ['in', array_column(array_values($touser), 'authcode')]])->getField('id, sex, yqr, yqm, authcode');
                    $touser = $touser + $touser_real;
                }
                if ($words) {
                    // 心动数+1
                    M('user')->where(['id' => ['in', $ids]])->setInc('heart');

                    $visitors = $seeRecord->where(['user_id' => $user_privacy['id'], 'the_user' => ['in', $ids]])->getField('the_user, id');

                    $insert = [];
                    $update = [];
                    $timenow = time();

                    //$type = $word['channel'] == 1 ? 2 : 0;
                    foreach ($ids as $item) {
                        $item_real = $item;
                        $item_real = $touser[$item]['authcode'] ? $item : $touser[$item]['authcode'];
                        if (isset($visitors[$item])) {
                            $update[] = ['id' => $visitors[$item], 'is_read' => 0, 'addtime' => date('Y-m-d H:i:s')];
                        } else {
                            $insert[] = ['user_id' => $user_privacy['id'], 'the_user' => $item];
                        }

                        $rand = mt_rand(0, count($word_ids) - 1);
                        $word = $words[$word_ids[$rand]];
                        $wordChannel = [2,0,1];
                        $type = $wordChannel[$word['channel'] - 1] ?? 0;
                        $second = $word['voice_time'];
                        $this->addTalk($user_privacy['id'], $item, $type, $word['content'], $second, '', 1, 0, 0, 0, 0, 1, 0, 0, $return, $front_id, $is_public);



                        $ChatChargeRecordsMap = $item_real < $user['id'] ? [
                            'user_id' => $item_real,
                            'another_id' => $user['id'],
                        ] :  [
                            'user_id' => $user['id'],
                            'another_id' => $item_real,
                        ];
                        $ChatChargeRecords = M('chat_charge_records')->master(true)->where($ChatChargeRecordsMap)->find();
                        if (!$ChatChargeRecords) {
                            if ($types == 2) {
                                $ChatChargeRecordsMap['payer'] = $item_real;
                                $ChatChargeRecordsMap['state'] = 0;
                                if ($user['yqr'] && $user['yqr'] == $touser[$item_real]['yqm']) {
                                    $ChatChargeRecordsMap['payer'] = $user['id'];
                                    $ChatChargeRecordsMap['state'] = 1;
                                } else if ($user['yqm'] && $user['yqm'] == $touser[$item_real]['yqr']) {
                                    $ChatChargeRecordsMap['payer'] = $item;
                                    $ChatChargeRecordsMap['state'] = 1;
                                }
                                $ChatChargeRecordsMap['time'] = $timenow;
                                M('chat_charge_records')->add($ChatChargeRecordsMap);
                                
                                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $user['id'], json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $item]));
                                Gateway::sendToUid(getenv('SOCKET_PREFIX') . $item_real, json_encode(['action' => 'api/Privatechat/changeChatPayer', 'touserid' => $user_privacy['id']]));
                            }
                        }
                    }


                    if ($insert) {
                        $seeRecord->addAll($insert);
                    }

                    foreach ($update as $key => $item) {
                        $seeRecord->save($item);
                    }
                }
            }
        }
        
    }

    public function clearfirst()
    {
        $user_id = I('user_id');
        $userInfo = M('user')->where(['id'=>$user_id])->field('id, sex')->cache(86400)->find();
        if($userInfo['sex'] == '女'){
            $sql1 = "update chat_lists set user_delete=1 WHERE user_id = $user_id and user_delete = 0 and user_first = 1";
            $sql2 = "update chat_lists set another_delete=1 WHERE another_id = $user_id and another_delete = 0 and another_first = 1";
        }else{
            $sql1 = "update chat_lists set user_delete=1 WHERE user_id = $user_id and user_delete = 0 and another_first = 1";
            $sql2 = "update chat_lists set another_delete=1 WHERE another_id = $user_id and another_delete = 0 and user_first = 1";
        }
        $datasql1 = M()->execute($sql1);
        $datasql2 = M()->execute($sql2);
        exit(json_encode(['code' => 200, 'msg' => '清理成功']));
    }

}
